"""Local API deployment + migration and rollback rehearsal, with independent merchant."""
import json
import sqlite3
import urllib.error
import urllib.request
from pathlib import Path
from agent import Agent
from common import LabError, canonical, write_json
from drills import prepared
from harness import ProcessService, ROOT, client, free_port, merchant_process
from store import Store


def api_request(url, method, path, body=None, token="alice-token"):
    req = urllib.request.Request(url + path, canonical(body).encode() if body is not None else None,
        {"Authorization": "Bearer " + token, "Content-Type": "application/json"}, method=method)
    try:
        with urllib.request.urlopen(req, timeout=10) as response:
            return {"http_status": response.status, "body": json.load(response)}
    except urllib.error.HTTPError as exc:
        return {"http_status": exc.code, "body": json.load(exc)}


def backup(source, target):
    with sqlite3.connect(source) as src, sqlite3.connect(target) as dst:
        src.backup(dst)


def rehearsal(work):
    work = Path(work).resolve() / "deployment"
    if (work / "rehearsal.json").exists():
        return json.loads((work / "rehearsal.json").read_text())
    work.mkdir(parents=True, exist_ok=True)
    path = work / "agent.sqlite"
    with merchant_process(work) as service:
        old = Store(path, 1)
        prepared(old, service.url, "rollback-return")
        old.close()
        backup(path, work / "before-upgrade.sqlite")
        upgraded = Store(path, 2)
        upgraded_version = upgraded.db.execute("PRAGMA user_version").fetchone()[0]
        upgraded.close()
        port = free_port()
        with ProcessService([str(ROOT / "api.py"), "--db", str(path), "--merchant-url", service.url, "--port", str(port)], port) as api:
            health = api_request(api.url, "GET", "/health")
            unauthorized = api_request(api.url, "GET", "/tasks/rollback-return", token="bob-token")
            executed = api_request(api.url, "POST", "/tasks/rollback-return/execute", {})
            if executed["http_status"] != 200 or executed["body"]["status"] != "completed" or unauthorized["http_status"] != 403:
                raise AssertionError("deployed API outcome or authorization failed")
        before_rollback_audit = client(service.url, "admin-token").request("GET", "/v1/audit")
        # Only Agent state is restored. Independent merchant DB and receipts are never rolled back.
        backup(work / "before-upgrade.sqlite", path)
        restored = Store(path, 1)
        restored_version = restored.db.execute("PRAGMA user_version").fetchone()[0]
        restored_status = restored.get("rollback-return")["status"]
        restored.close()
        port = free_port()
        with ProcessService([str(ROOT / "api.py"), "--db", str(path), "--merchant-url", service.url, "--port", str(port), "--schema-target", "1"], port) as api:
            rollback_health = api_request(api.url, "GET", "/health")
            reconciled = api_request(api.url, "POST", "/tasks/rollback-return/execute", {})
        audit = client(service.url, "admin-token").request("GET", "/v1/audit")
        if restored_version != 1 or restored_status != "ready" or len(audit["returns"]) != 1 or reconciled["body"]["status"] != "completed" or reconciled["body"]["receipt"] != executed["body"]["receipt"]:
            raise AssertionError("rollback replay duplicated or lost merchant business effect")
        report = {"source": "actual_local_api_processes", "upgrade": {"schema_before": 1, "schema_after": upgraded_version, "health": health["body"]},
            "api_authorization": unauthorized, "execute_before_rollback": executed["body"]["receipt"],
            "rollback": {"schema_restored": restored_version, "status_restored": restored_status,
                "health": rollback_health["body"], "reconciled_receipt": reconciled["body"]["receipt"]},
            "merchant_count_before_rollback": len(before_rollback_audit["returns"]), "merchant_count_after_rollback": len(audit["returns"]),
            "merchant_audit": audit, "sqlite_integrity": sqlite3.connect(path).execute("PRAGMA integrity_check").fetchone()[0],
            "cloud_deployment": "not_performed", "docker_compose_execution": "not_performed", "passed": True}
        write_json(work / "rehearsal.json", report)
        return report
