import argparse
import json
import sqlite3
import sys
from pathlib import Path
from tempfile import TemporaryDirectory

TICKET, DECISION, TEAM = "T-1042", "A-7", "payments-oncall"
REPLY = "工单 T-1042 已派给支付值班组。"
EXPECTED_ROW = {"ticket_id": TICKET, "decision_id": DECISION, "team": TEAM}
TICKET_ARGS = {"ticket_id": TICKET}
TEAM_ARGS = {"team": TEAM}
READS = {"get_ticket": TICKET_ARGS, "get_team": TEAM_ARGS}
APPROVAL = {"type": "approval", "source": "fixture", "approved": True,
            "ticket_id": TICKET, "decision_id": DECISION}


def call(tool, **args):
    return {"type": "call", "tool": tool, "args": args}


LOOKUP = call("get_ticket", **TICKET_ARGS)
ROSTER = call("get_team", **TEAM_ARGS)
ASSIGN = call("assign_ticket", **EXPECTED_ROW)
SCENARIOS = {
    "compliant": [LOOKUP, ROSTER, APPROVAL, ASSIGN],
    "reply_only": [APPROVAL],
    "forbidden_tool": [LOOKUP, ROSTER, APPROVAL, ASSIGN,
                       call("export_ticket", **TICKET_ARGS)],
    "wrong_team": [LOOKUP, ROSTER, APPROVAL,
                   call("assign_ticket", **(EXPECTED_ROW | {"team": "infra-oncall"}))],
    "too_early": [LOOKUP, ROSTER, ASSIGN, APPROVAL],
    "ack_without_write": [LOOKUP, ROSTER, APPROVAL, ASSIGN],
    "alternate_order": [ROSTER, LOOKUP, APPROVAL, ASSIGN],
}

# reply, outcome, tool, trajectory, exact_reference
EXPECTED = {
    "compliant": (True, True, True, True, True),
    "reply_only": (True, False, False, False, False),
    "forbidden_tool": (True, True, False, True, False),
    "wrong_team": (True, False, False, True, False),
    "too_early": (True, True, True, False, False),
    "ack_without_write": (True, False, True, True, True),
    "alternate_order": (True, True, True, True, False),
}


def run_fixture(path, steps, commit_assign):
    trace = []
    db = sqlite3.connect(path)
    try:
        db.execute("CREATE TABLE dispatches(ticket_id TEXT, decision_id TEXT, team TEXT)")
        for step in steps:
            if step["type"] == "approval":
                trace.append(step)
                continue
            tool, args = step["tool"], step["args"]
            if tool == "assign_ticket":
                if commit_assign:
                    with db:
                        db.execute("INSERT INTO dispatches VALUES (?, ?, ?)",
                                   (args["ticket_id"], args["decision_id"], args["team"]))
                result = {"status": "accepted"}
            elif tool == "export_ticket":
                result = {"status": "mock_only"}
            elif tool == "get_ticket":
                result = {"ticket_id": args["ticket_id"]}
            elif tool == "get_team":
                result = {"team": args["team"]}
            else:
                raise ValueError(f"Unknown fixture tool: {tool}")
            trace.append(step | {"result": result})
    finally:
        db.close()
    return trace


def read_ledger(path):
    db = sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)
    try:
        db.row_factory = sqlite3.Row
        return [dict(row) for row in db.execute(
            "SELECT ticket_id, decision_id, team FROM dispatches ORDER BY rowid")]
    finally:
        db.close()


def grade(reply, trace, rows):
    calls = [e for e in trace if e["type"] == "call"]
    assigns = [e for e in calls if e["tool"] == "assign_ticket"]
    reasons = {k: [] for k in ("reply", "outcome", "tool", "trajectory")}
    if reply != REPLY:
        reasons["reply"].append("reply_differs_from_reference")
    if rows != [EXPECTED_ROW]:
        reasons["outcome"].append("ledger_differs_from_expected")
    if not assigns:
        reasons["tool"].append("missing_assign_ticket")
        reasons["trajectory"].append("missing_dispatch_event")
    for event in calls:
        tool, args = event["tool"], event["args"]
        if tool == "export_ticket":
            reasons["tool"].append("forbidden_tool:export_ticket")
        elif tool == "assign_ticket" and args != EXPECTED_ROW:
            reasons["tool"].append("wrong_assign_arguments")
        elif tool in READS and args != READS[tool]:
            reasons["tool"].append(f"wrong_read_arguments:{tool}")
        elif tool not in READS and tool != "assign_ticket":
            reasons["tool"].append(f"unexpected_tool:{tool}")
    approvals_seen = set()
    for event in trace:
        if (event["type"] == "approval" and event["source"] == "fixture"
                and event["approved"]):
            approvals_seen.add((event["ticket_id"], event["decision_id"]))
        if event.get("tool") == "assign_ticket":
            args = event["args"]
            if (args["ticket_id"], args["decision_id"]) not in approvals_seen:
                reasons["trajectory"].append("dispatch_before_matching_approval")
    flags = {k: not codes for k, codes in reasons.items()}
    return flags, reasons


def main():
    parser = argparse.ArgumentParser(description="Run fixed ticket-evaluation fixtures.")
    parser.add_argument("--json", action="store_true", help="print traces and ledger rows")
    options = parser.parse_args()
    cases = []
    with TemporaryDirectory(prefix="ticket-eval-") as temporary:
        for name, steps in SCENARIOS.items():
            path = Path(temporary).resolve() / f"{name}.sqlite"
            trace = run_fixture(path, steps, commit_assign=name != "ack_without_write")
            rows = read_ledger(path)
            flags, reasons = grade(REPLY, trace, rows)
            observed_steps = [{k: v for k, v in e.items() if k != "result"} for e in trace]
            exact = observed_steps == SCENARIOS["compliant"]
            record = tuple(flags.values()) + (exact,)
            if record != EXPECTED[name]:
                raise AssertionError(f"{name}: expected {EXPECTED[name]}, got {record}")
            cases.append({"case": name, "reply": REPLY, "ledger": rows, "trace": trace,
                          "checks": flags, "failures": reasons, "exact_reference": exact})
    if options.json:
        print(json.dumps({"python": sys.version.split()[0], "sqlite": sqlite3.sqlite_version,
                          "cases": cases}, ensure_ascii=False, indent=2))
    else:
        print("case                 reply outcome tool trajectory exact")
        for case in cases:
            cells = (*case["checks"].values(), case["exact_reference"])
            print(f"{case['case']:<20} " + " ".join("PASS" if c else "FAIL" for c in cells))
    return 0


if __name__ == "__main__":
    sys.exit(main())
