#!/usr/bin/env python3
"""Contract test for prompt-defined CARBON tests and legacy-to-intent conversion."""

from __future__ import annotations

import json
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
INTENT = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_intent.py"
FRAMEWORK = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_framework.py"


def run(*args: str, ok: bool = True) -> subprocess.CompletedProcess[str]:
    result = subprocess.run(args, capture_output=True, text=True)
    if ok and result.returncode:
        raise AssertionError(f"Command failed: {' '.join(args)}\n{result.stdout}\n{result.stderr}")
    if not ok and result.returncode == 0:
        raise AssertionError(f"Command unexpectedly succeeded: {' '.join(args)}")
    return result


def write(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def write_xlsx(path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    sheet = """<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>
    <row r="1"><c r="A1" t="inlineStr"><is><t>Case ID</t></is></c><c r="B1" t="inlineStr"><is><t>Title</t></is></c><c r="C1" t="inlineStr"><is><t>Preconditions</t></is></c><c r="D1" t="inlineStr"><is><t>Steps</t></is></c><c r="E1" t="inlineStr"><is><t>Expected Result</t></is></c></row>
    <row r="2"><c r="A2" t="inlineStr"><is><t>C901</t></is></c><c r="B2" t="inlineStr"><is><t>Spreadsheet checkout intent</t></is></c><c r="C2" t="inlineStr"><is><t>Synthetic cart</t></is></c><c r="D2" t="inlineStr"><is><t>Submit checkout</t></is></c><c r="E2" t="inlineStr"><is><t>One order is created</t></is></c></row>
    </sheetData></worksheet>"""
    with zipfile.ZipFile(path, "w") as archive:
        archive.writestr("xl/worksheets/sheet1.xml", sheet)


def write_docx(path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    document = """<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>
    <w:p><w:r><w:t>Test Case: Guest cannot edit billing</w:t></w:r></w:p>
    <w:p><w:r><w:t>Navigate to billing and click Edit.</w:t></w:r></w:p>
    <w:p><w:r><w:t>Then verify the sign-in prompt is visible.</w:t></w:r></w:p>
    </w:body></w:document>"""
    with zipfile.ZipFile(path, "w") as archive:
        archive.writestr("word/document.xml", document)


def main() -> int:
    with tempfile.TemporaryDirectory(prefix="carbon-intent-") as temporary:
        root = Path(temporary)
        write(root / "src" / "editor.tsx", "export const Editor = () => <textarea aria-label='Draft' />;\n")
        legacy = root / "legacy"
        write(
            legacy / "editor.spec.ts",
            """import { test, expect } from '@playwright/test';
test('draft survives reconnect', async ({ page }) => {
  await page.goto('/editor/1');
  await page.fill('[data-testid=draft]', 'hello');
  await page.click('[data-testid=save]');
  await expect(page.getByText('Saved')).toBeVisible();
});
test('viewer cannot edit', async ({ page }) => {
  await page.goto('/editor/1');
  await expect(page.getByRole('button', { name: 'Save' })).toBeDisabled();
});
""",
        )
        write(
            legacy / "manual.csv",
            "title,preconditions,steps,expected\nExport preserves Unicode,Signed-in editor,Export one draft,Downloaded content matches the source\n",
        )
        write(
            legacy / "testrail-export.csv",
            "Case ID,Title,Section,Preconditions,Steps,Expected Result\nC101,Refund is idempotent,Payments,Synthetic paid order,Request the same refund twice,Exactly one refund is durable\n",
        )
        write(
            legacy / "xray-export.json",
            json.dumps({"tests": [{"testKey": "PAY-22", "testInfo": {"summary": "Expired card is declined", "description": "Validate a safe declined payment"}, "steps": [{"content": "Submit an expired synthetic card", "expectedResult": "No order is created and decline is visible"}]}]}),
        )
        write(
            legacy / "testrail-export.xml",
            "<suite><cases><case><id>C202</id><title>Viewer cannot refund</title><preconditions>Viewer role</preconditions><steps><step>Request refund</step></steps><expected>Authorization is denied and no refund is created</expected></case></cases></suite>",
        )
        write_xlsx(legacy / "testrail-spreadsheet.xlsx")
        write_docx(legacy / "manual-cases.docx")

        initialized = json.loads(run(sys.executable, str(INTENT), "init", "--root", str(root)).stdout)
        assert Path(initialized["library"]).exists()
        created = json.loads(run(
            sys.executable, str(INTENT), "create", "--root", str(root),
            "--prompt", "When an editor reconnects, preserve unsaved text and complete exactly one durable save.",
            "--title", "Reconnect preserves draft", "--scope", "editor draft flow",
            "--setup", "Signed-in synthetic editor", "--expected", "Unsaved text remains visible",
            "--expected", "Exactly one save persists after reconnect", "--priority", "P1", "--status", "active",
        ).stdout)
        assert created["status"] == "active" and created["readiness"]["band"] == "high"
        prompt_id = created["id"]

        updated = json.loads(run(
            sys.executable, str(INTENT), "update", "--root", str(root), "--id", prompt_id,
            "--tag", "offline", "--tag", "resilience",
        ).stdout)
        assert updated["revision"] == 2 and updated["tags"] == ["offline", "resilience"]
        copied = json.loads(run(sys.executable, str(INTENT), "duplicate", "--root", str(root), "--id", prompt_id).stdout)
        assert copied["id"] != prompt_id and copied["status"] == "draft"
        run(sys.executable, str(INTENT), "status", "--root", str(root), "--id", copied["id"], "--status", "archived")
        run(sys.executable, str(INTENT), "delete", "--root", str(root), "--id", copied["id"], ok=False)
        run(sys.executable, str(INTENT), "delete", "--root", str(root), "--id", copied["id"], "--confirm")

        imported = json.loads(run(sys.executable, str(INTENT), "import", "--root", str(root), "--source", str(legacy)).stdout)
        assert imported["imported"] == 8 and imported["failed"] == 0
        assert imported["bakeRun"]["summary"]["total"] == 8
        assert Path(imported["bakeRun"]["report"]).exists()
        assert all(row["readiness"]["missing"] for row in imported["drafts"])
        repeated = json.loads(run(sys.executable, str(INTENT), "import", "--root", str(root), "--source", str(legacy)).stdout)
        assert repeated["imported"] == 0 and repeated["skipped"] == 8

        listing = json.loads(run(sys.executable, str(INTENT), "list", "--root", str(root)).stdout)
        assert listing["count"] == 9
        library = json.loads((root / ".carbon" / "tests" / "intent-tests.json").read_text())
        legacy_tests = [test for test in library["tests"] if test["source"]["kind"] == "legacy"]
        assert {test["source"]["framework"] for test in legacy_tests} == {"playwright", "tabular-manual", "testrail", "xray", "document-manual"}
        assert {test["source"].get("externalId") for test in legacy_tests} >= {"C101", "C202", "C901", "PAY-22"}
        xray = next(test for test in legacy_tests if test["source"].get("externalId") == "PAY-22")
        assert "Submit an expired synthetic card" in xray["legacySteps"]
        assert all(test["status"] == "draft" and test["lifecycle"] == "candidate" for test in legacy_tests)
        assert all(test["source"]["sha256"] and "legacySteps" in test for test in legacy_tests)

        exported = root / "intent-prompts.md"
        run(sys.executable, str(INTENT), "export", "--root", str(root), "--output", str(exported), "--format", "prompts")
        assert prompt_id in exported.read_text() and "Exactly one save" in exported.read_text()

        run(sys.executable, str(FRAMEWORK), "prepare", "--root", str(root), "--request", "test this", "--target", "http://localhost:3000")
        plan = json.loads((root / ".carbon" / "framework" / "orchestration-plan.json").read_text())
        candidate_pool = json.loads((root / ".carbon" / "framework" / "candidate-pool.json").read_text())
        intent_case = next(test for test in candidate_pool["tests"] if test["id"] == prompt_id)
        assert intent_case["type"] == "intent" and intent_case["priority"] == "P1"
        assert "Exactly one save persists" in intent_case["oracle"]
        assert prompt_id in {test["id"] for test in plan["tests"]} or prompt_id in plan["deferredTestIds"]

        run(
            sys.executable, str(INTENT), "create", "--root", str(root),
            "--prompt", "Use bearer abcdefghijklmnopqrstuvwxyz123456 to test this", ok=False,
        )

    print("CARBON AI-intent test library contract: PASS")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
