#!/usr/bin/env python3
"""Contract test for private local CARBON Feedback state and report output."""

from __future__ import annotations

import json
import subprocess
import tempfile
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
SCRIPT = PLUGIN / "runtime" / "carbon" / "scripts" / "carbon_feedback.py"
WORKSPACE = PLUGIN / "ui" / "feedback.html"


def run(*args: str) -> dict:
    result = subprocess.run(["python3", str(SCRIPT), *args], check=True, capture_output=True, text=True)
    return json.loads(result.stdout)


with tempfile.TemporaryDirectory(prefix="carbon-feedback-contract-") as temporary:
    root = Path(temporary)
    (root / "package.json").write_text(json.dumps({"name": "feedback-demo"}), encoding="utf-8")
    created = run(
        "create", "--root", str(root), "--title", "Checkout first look", "--focus", "Tell us whether checkout feels credible and where a customer would lose trust.",
        "--artifact", "https://example.test/checkout", "--artifact-kind", "url", "--context", "Synthetic staging data only.",
    )
    request = created["request"]
    assert request["id"].startswith("FBK-")
    assert request["delivery"]["mode"] == "local"
    state = root / ".carbon" / "feedback" / "requests.json"
    assert state.is_file() and state.stat().st_mode & 0o777 == 0o600

    response = run("respond", "--root", str(root), "--request", request["id"], "--rating", "3", "--category", "trust", "--response", "The total is clear, but the confirm action lacks reassurance.")
    assert response["response"]["rating"] == 3
    note = run("comment", "--root", str(root), "--request", request["id"], "--comment", "Review this with a first-time customer persona.")
    assert note["comment"]["comment"].startswith("Review this")
    delivery = run("delivery", "--root", str(root), "--request", request["id"], "--status", "queued", "--message", "Private service accepted the request.", "--reviewer-url", "https://feedback.example.internal/review/CFB-demo#capability")
    assert delivery["request"]["delivery"]["mode"] == "private-service"
    synced = run("sync", "--root", str(root), "--request", request["id"], "--responses-json", json.dumps([{"id": "remote-1", "rating": 5, "category": "value", "response": "The value is obvious as soon as the summary appears.", "createdAt": "2026-08-28T19:00:00Z"}]))
    assert synced["importedResponses"][0]["source"] == "private-feedback-service"
    report = run("report", "--root", str(root))
    report_path = Path(report["report"]["reportPath"])
    html = report_path.read_text(encoding="utf-8")
    assert report_path.is_file()
    assert "Private feedback loop" in html and 'rel="icon"' in html and "AI" in html

workspace = WORKSPACE.read_text(encoding="utf-8")
assert "/api/feedback-context" in workspace
assert "Record local feedback" in workspace and "Private feedback workspace" in workspace
assert "alert(" not in workspace and "confirm(" not in workspace

service = (PLUGIN / "feedback-service" / "server.mjs").read_text(encoding="utf-8")
assert "reviewerTokenHash" in service and "CARBON_FEEDBACK_MAIL_WEBHOOK_URL" in service and "SMTP_URL" in service
assert "no public\nfallback" in (PLUGIN / "feedback-service" / "README.md").read_text(encoding="utf-8").lower()

print("PASS: local feedback requests, qualitative response state, durable report, non-secret private delivery state, workspace, and self-hosted service contracts verified.")
