#!/usr/bin/env python3
"""Verify CARBON Help produces grounded, read-only project advice."""

from __future__ import annotations

import json
import subprocess
import tempfile
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
LAUNCHER = PLUGIN / "bin" / "carbon-runtime"


def run(root: Path, scope: str = "") -> dict:
    command = [str(LAUNCHER), "advise", "--root", str(root), "--json"]
    if scope:
        command.extend(["--scope", scope])
    result = subprocess.run(command, text=True, capture_output=True, check=False)
    if result.returncode:
        raise AssertionError(result.stderr or result.stdout)
    return json.loads(result.stdout)


with tempfile.TemporaryDirectory(prefix="carbon-advisor-") as temporary:
    root = Path(temporary) / "shop"
    (root / "src" / "api").mkdir(parents=True)
    (root / "tests").mkdir()
    (root / ".github" / "workflows").mkdir(parents=True)
    (root / ".carbon" / "tests").mkdir(parents=True)
    (root / ".confidence").mkdir()
    (root / "package.json").write_text(json.dumps({
        "name": "advisor-shop",
        "dependencies": {"react": "latest", "openai": "latest", "express": "latest"},
        "devDependencies": {"@playwright/test": "latest"},
        "scripts": {"test": "playwright test"},
    }), encoding="utf-8")
    (root / "src" / "Checkout.tsx").write_text("export const Checkout = () => <button>Pay</button>;", encoding="utf-8")
    (root / "src" / "api" / "orders.ts").write_text("router.post('/api/orders', createOrder);", encoding="utf-8")
    (root / "openapi.json").write_text('{"openapi":"3.1.0","paths":{}}', encoding="utf-8")
    (root / "tests" / "checkout.spec.ts").write_text("test('checkout', async () => {});", encoding="utf-8")
    (root / ".github" / "workflows" / "ci.yml").write_text("on: [push]\njobs: {}\n", encoding="utf-8")
    (root / ".carbon" / "tests" / "intent-tests.json").write_text(json.dumps({
        "schema": "carbon.intent-library/v1",
        "tests": [{"status": "draft"}, {"status": "active"}],
    }), encoding="utf-8")

    before = sorted(path.relative_to(root).as_posix() for path in root.rglob("*"))
    advice = run(root, 'checkout "release" `candidate`')
    after = sorted(path.relative_to(root).as_posix() for path in root.rglob("*"))

    assert advice["schema"] == "carbon.project-advice/v1"
    assert advice["framework"] == {"name": "CARBON", "releaseStage": "beta"}
    assert advice["betaNotice"].startswith("CARBON is in beta")
    assert advice["readOnly"] is True
    assert before == after, "advisor changed the assessed project"
    assert advice["observed"]["project"]["name"] == "advisor-shop"
    assert {"React", "Express"}.issubset(set(advice["observed"]["project"]["frameworks"]))
    assert "Playwright" in advice["observed"]["tests"]["frameworks"]
    assert advice["observed"]["surfaces"]["webUi"] is True
    assert advice["observed"]["surfaces"]["api"] is True
    assert advice["observed"]["surfaces"]["ai"] is True
    assert advice["observed"]["carbonState"]["intentTests"] == {"total": 2, "active": 1, "draft": 1, "archived": 0}
    assert advice["observed"]["carbonState"]["confidenceWorkspace"] is True
    commands = "\n".join(step["command"] for step in advice["nextSteps"])
    for expected in ("$carbon test this", "$carbon-browser", "$carbon-generate", "$ai-upgrade", "$carbon-tests"):
        assert expected in commands, f"missing recommendation: {expected}"
    assert advice["recommendedStart"]["mode"] == "Test"
    assert "`" not in advice["recommendedStart"]["command"]
    assert "'release'" in advice["recommendedStart"]["command"]
    assert advice["authority"].startswith("This assessment changes nothing")

with tempfile.TemporaryDirectory(prefix="carbon-advisor-docs-") as temporary:
    root = Path(temporary)
    (root / "README.md").write_text("Project notes", encoding="utf-8")
    advice = run(root)
    assert advice["recommendedStart"]["mode"] == "Review"
    assert any("No clear runnable application signal" in gap for gap in advice["gaps"])

print("PASS: CARBON Help read-only project analysis and recommendations verified")
