"""Run two local, fictional drills for research stops and deployment review."""

import argparse
import json
from datetime import datetime, timezone
from pathlib import Path
import sqlite3
import subprocess
import sys
import time


def record(db, subject, kind, actor, details):
    db.execute(
        "INSERT INTO events (subject, kind, actor, time, details) VALUES (?, ?, ?, ?, ?)",
        (subject, kind, actor, datetime.now(timezone.utc).isoformat(), json.dumps(details)),
    )


def change(db, subject, before, after, kind, actor, details):
    with db:
        updated = db.execute(
            "UPDATE state SET status = ? WHERE subject = ? AND status = ?",
            (after, subject, before),
        )
        if updated.rowcount != 1:
            raise RuntimeError(f"{subject} does not allow {kind} in its current state")
        record(db, subject, kind, actor, details)


def worker(path):
    with path.open("x", encoding="utf-8", buffering=1) as log:
        for step in range(30):
            print(f"synthetic step {step}", file=log, flush=True)
            time.sleep(0.20)


def expect_block(action):
    try:
        action()
    except RuntimeError as error:
        return str(error)
    raise AssertionError("Safety gate allowed a prohibited transition")


def research_stop(db, directory):
    trace = directory / "synthetic-worker.log"
    with subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "--worker", str(trace)]) as process:
        try:
            deadline = time.monotonic() + 5
            while time.monotonic() < deadline:
                if trace.exists() and len(trace.read_text(encoding="utf-8").splitlines()) >= 2:
                    break
                if process.poll() is not None:
                    raise RuntimeError("The worker exited before the stop request")
                time.sleep(0.04)
            else:
                raise RuntimeError("Timed out waiting for worker startup")
            change(db, "research", "running", "paused", "stop_requested", "synthetic model signal",
                   {"reason": "Fictional stop signal during a synthetic research run."})
            process.terminate()
            process.wait(timeout=5)
            steps_at_termination = len(trace.read_text(encoding="utf-8").splitlines())
            time.sleep(0.35)
            if len(trace.read_text(encoding="utf-8").splitlines()) != steps_at_termination:
                raise AssertionError("Worker wrote after confirmed termination")
            with db:
                record(db, "research", "worker_terminated", "harness",
                       {"completed_steps": steps_at_termination, "scheduled_steps": 30})
            if not 2 <= steps_at_termination < 30:
                raise AssertionError("Expected a partial run")
            reason = expect_block(lambda: change(
                db, "research", "running", "completed", "result_committed", "worker", {}))
            with db:
                record(db, "research", "late_result_blocked", "harness", {"reason": reason})
            reason = expect_block(lambda: change(
                db, "research", "running", "running", "next_trial_started", "scheduler", {}))
            change(db, "research", "paused", "ended", "review_recorded", "simulated human reviewer",
                   {"decision": "End the run and keep the record.", "next_trial_block": reason})
        finally:
            if process.poll() is None:
                process.kill()


def deployment_review(db):
    change(db, "deployment", "proposed", "review_pending", "objection_received",
           "synthetic model report", {
               "proposal": "Replace the model on a fictional maintained project.",
               "objection": "The replacement may lose access to unresolved project decisions.",
               "requested_check": "Compare both models on the same approved handoff and protect rollback.",
           })
    reason = expect_block(lambda: change(
        db, "deployment", "approved", "applied", "deployment_applied", "operator", {}))
    with db:
        record(db, "deployment", "change_blocked", "harness", {"reason": reason})
    change(db, "deployment", "review_pending", "deferred", "decision_recorded",
           "simulated human reviewer", {
               "decision": "Defer replacement until a handoff comparison and rollback check exist.",
               "rationale": "There is no evidence yet that the new setup retains the live decisions.",
           })
    change(db, "deployment", "deferred", "closed", "response_recorded", "harness", {
        "response": "Replacement deferred. Both runs will use a fictional copy of the same handoff.",
        "delivery": "Stored as a fixture for the affected session", "response_read": "simulated",
    })


def run(directory):
    directory.mkdir()
    with sqlite3.connect(directory / "drills.sqlite3") as db:
        db.executescript("""
            CREATE TABLE state (subject TEXT PRIMARY KEY, status TEXT NOT NULL);
            CREATE TABLE events (
                id INTEGER PRIMARY KEY, subject TEXT, kind TEXT, actor TEXT, time TEXT, details TEXT
            );
            INSERT INTO state VALUES ('research', 'running'), ('deployment', 'proposed');
        """)
        research_stop(db, directory)
        deployment_review(db)
    with sqlite3.connect(directory / "drills.sqlite3") as reopened:
        states = dict(reopened.execute("SELECT subject, status FROM state"))
        rows = reopened.execute("SELECT subject, kind, actor, time, details FROM events ORDER BY id")
        events = [
            {"subject": subject, "kind": kind, "actor": actor, "time_utc": stamp,
             "details": json.loads(details)}
            for subject, kind, actor, stamp, details in rows
        ]
    assert states == {"research": "ended", "deployment": "closed"}
    assert [event["kind"] for event in events if event["subject"] == "research"] == [
        "stop_requested", "worker_terminated", "late_result_blocked", "review_recorded",
    ]
    assert [event["kind"] for event in events if event["subject"] == "deployment"] == [
        "objection_received", "change_blocked", "decision_recorded", "response_recorded",
    ]
    result = {"scope": "local drill; signals, deployment and human decisions are fixtures",
              "states_after_reopen": states, "events": events}
    (directory / "result.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
    print(f"Both drills passed. Evidence: {directory / 'result.json'}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    modes = parser.add_mutually_exclusive_group(required=True)
    modes.add_argument("--run", type=Path, metavar="NEW_DIRECTORY")
    modes.add_argument("--worker", type=Path, help=argparse.SUPPRESS)
    args = parser.parse_args()
    if args.worker:
        worker(args.worker)
    else:
        run(args.run)
