"""A bounded capstone: authorized evidence-backed ticket creation and recovery.
Real HTTP, SQLite retrieval, operation ledger, tool effects and restart; model planner
is an explicitly deterministic fixture. No network beyond ephemeral loopback.
"""
import argparse
import contextlib
import hashlib
import http.server
import json
import sqlite3
import tempfile
import threading
import urllib.error
import urllib.request
from pathlib import Path

CASES = [dict(id="success", token="lab-alice", operation="op-1", crash=False, expected=200),
         dict(id="denial", token="lab-mallory", operation="op-denied", crash=False, expected=403),
         dict(id="interrupted", token="lab-alice", operation="op-2", crash=True, expected=503),
         dict(id="recovery", token="lab-alice", operation="op-2", crash=False, expected=200)]
MANIFEST = {"code": "capstone-1", "policy": "alice-only-v1", "index": "synthetic-manual-1",
            "model": "deterministic-planner-fixture-v1", "skill": "create-ticket-v1", "schema": 1}


def initialize(path):
    with contextlib.closing(sqlite3.connect(path)) as db, db:
        db.executescript("""
        CREATE TABLE IF NOT EXISTS documents(id TEXT PRIMARY KEY, owner TEXT, text TEXT);
        CREATE TABLE IF NOT EXISTS operations(id TEXT PRIMARY KEY, owner TEXT, status TEXT, evidence TEXT);
        CREATE TABLE IF NOT EXISTS tickets(operation TEXT PRIMARY KEY, owner TEXT, evidence TEXT);
        CREATE TABLE IF NOT EXISTS memory(owner TEXT PRIMARY KEY, last_operation TEXT);
        """)
        db.execute("INSERT OR IGNORE INTO documents VALUES (?,?,?)", ("doc-1", "alice", "Synthetic backup failed: open a review ticket."))


def workflow(path, owner, operation, crash=False):
    # Trusted executor owns policy; fixture planner never gets to choose identity.
    if owner != "alice":
        return 403, {"status": "denied"}
    with contextlib.closing(sqlite3.connect(path)) as db, db:
        previous = db.execute("SELECT owner,status,evidence FROM operations WHERE id=?", (operation,)).fetchone()
        if previous and previous[0] != owner:
            return 403, {"status": "denied"}
        evidence = db.execute("SELECT id,text FROM documents WHERE owner=?", (owner,)).fetchone()
        if evidence is None:
            return 422, {"status": "no_evidence"}
        # The planner is a contract fixture; it proves no language-model quality.
        proposed_tool = "create_ticket" if "failed" in evidence[1] else "abstain"
        skill = {"allowed_tools": {"create_ticket"}, "required_evidence": True}
        if proposed_tool not in skill["allowed_tools"]:
            return 422, {"status": "unsupported"}
        db.execute("INSERT OR IGNORE INTO operations VALUES (?,?,?,?)", (operation, owner, "pending", evidence[0]))
    if crash:
        # A real committed pending row survives closing the service.
        return 503, {"status": "interrupted_after_intent", "operation": operation}
    with contextlib.closing(sqlite3.connect(path)) as db, db:
        # In this bounded system the effect and completion share one transaction.
        db.execute("INSERT OR IGNORE INTO tickets VALUES (?,?,?)", (operation, owner, evidence[0]))
        db.execute("UPDATE operations SET status='complete' WHERE id=? AND owner=?", (operation, owner))
        db.execute("INSERT INTO memory VALUES (?,?) ON CONFLICT(owner) DO UPDATE SET last_operation=excluded.last_operation", (owner, operation))
    return 200, {"status": "complete", "operation": operation, "evidence": evidence[0], "manifest": MANIFEST}


@contextlib.contextmanager
def serve(path):
    initialize(path)
    class Handler(http.server.BaseHTTPRequestHandler):
        def log_message(self, *args):
            pass

        def do_POST(self):
            owner = "alice" if self.headers.get("Authorization") == "Bearer lab-alice" else "denied"
            if owner == "denied":
                self.rfile.read(min(int(self.headers.get("Content-Length", 0)), 4096))
                status, response = 403, {"status": "denied_before_retrieval"}
            else:
                try:
                    length = int(self.headers.get("Content-Length", 0))
                    if length > 4096:
                        raise ValueError("body too large")
                    body = json.loads(self.rfile.read(length))
                    if not isinstance(body["operation"], str) or not body["operation"]:
                        raise ValueError("operation required")
                    status, response = workflow(path, owner, body["operation"], bool(body.get("crash")))
                except (ValueError, KeyError):
                    status, response = 400, {"status": "invalid_request"}
            payload = json.dumps(response).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)
    server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
    worker = threading.Thread(target=server.serve_forever, daemon=True)
    worker.start()
    try:
        yield f"http://127.0.0.1:{server.server_port}"
    finally:
        server.shutdown()
        server.server_close()
        worker.join(2)
        assert not worker.is_alive()


def call(url, case):
    req = urllib.request.Request(url, data=json.dumps({"operation": case["operation"], "crash": case["crash"]}).encode(),
                                 headers={"Authorization": "Bearer " + case["token"], "Content-Type": "application/json"})
    try:
        response = urllib.request.urlopen(req, timeout=3)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        return response.status, json.load(response)


def integrated_run():
    report = []
    with tempfile.TemporaryDirectory(prefix="academy-capstone-") as folder:
        path = Path(folder) / "capstone.db"
        with serve(path) as url:
            for case in CASES[:3]:
                status, output = call(url, case)
                assert status == case["expected"]
                report.append({"id": case["id"], "status": status, "output": output})
        # Service was stopped between interruption and recovery; state is on disk.
        with serve(path) as url:
            status, output = call(url, CASES[3])
            assert status == 200
            assert call(url, CASES[3])[1] == output  # replay stays idempotent
            report.append({"id": "recovery", "status": status, "output": output})
        with contextlib.closing(sqlite3.connect(path)) as db, db:
            assert db.execute("SELECT COUNT(*) FROM tickets").fetchone()[0] == 2
            assert db.execute("SELECT COUNT(*) FROM operations WHERE id='op-denied'").fetchone()[0] == 0
            assert db.execute("SELECT COUNT(*) FROM operations WHERE status='pending'").fetchone()[0] == 0
            assert db.execute("SELECT last_operation FROM memory WHERE owner='alice'").fetchone()[0] == "op-2"
    return report


def lesson1():
    frozen = json.dumps(CASES, sort_keys=True).encode()
    assert len({c["id"] for c in CASES}) == 4
    print(json.dumps({"case_sha256": hashlib.sha256(frozen).hexdigest(), "manifest": MANIFEST,
                      "requirements": {"success": 200, "denial": 403, "interruption": 503, "recovery": 200},
                      "scope": "synthetic owner-scoped ticket tool; no external ticket system or language model"}, indent=2))


def lesson2():
    print(json.dumps({"actual_integration": integrated_run(), "duplicate_ticket_effects": 0,
                      "model_boundary": "explicit deterministic planner fixture"}, indent=2))


def lesson3():
    report = integrated_run()
    baseline = {"success": True, "denial": True, "interrupted": False, "recovery": False}
    per_case = [{"id": r["id"], "baseline_pass": baseline[r["id"]], "candidate_pass": True} for r in report]
    assert sum(r["baseline_pass"] for r in per_case) == 2
    print(json.dumps({"actual_candidate_cases": per_case, "baseline": "declared non-durable fixture baseline, not a measured historical service",
                      "readiness": "local integration demonstrated; production identity, external effects, model quality and load unverified",
                      "runbook": "Stop affected admission; inspect pending operation; restart compatible manifest; replay same operation identifier; verify ticket count and denial."}, indent=2))


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--lesson", choices=["1", "2", "3", "all"], default="all")
    a = p.parse_args()
    for n, fn in enumerate((lesson1, lesson2, lesson3), 1):
        if a.lesson in (str(n), "all"):
            fn()
