"""90-day mmdc history with proper exit-code classification + detail of 06-23 failure. (ASCII safe)"""
import os
from pathlib import Path

env = Path(__file__).resolve().parent.parent / ".env"
for line in env.read_text(encoding="utf-8").splitlines():
    if line.strip().startswith("ZCBOT_DB_URL="):
        os.environ["ZCBOT_DB_URL"] = line.split("=", 1)[1].strip()
from sqlalchemy import create_engine, text  # noqa: E402

import builtins  # noqa: E402

_out = open(Path(__file__).resolve().parent / "_mmdc_history2.txt", "w", encoding="utf-8")


def print(*a, **k):  # noqa: A001
    builtins.print(*a, **k, file=_out)


engine = create_engine(os.environ["ZCBOT_DB_URL"])

with engine.connect() as conn:
    rows = conn.execute(text("""
        select m.task_id, m.idx, m.created_at, m.payload->>'content' as c
        from messages m
        where m.payload->>'role' = 'tool'
          and m.payload->>'content' like '%Generating single mermaid chart%'
          and m.created_at > now() - interval '90 days'
        order by m.created_at
    """)).fetchall()
    print(f"[MMDC RUNS last 90d] count={len(rows)}")
    for tid, idx, ca, c in rows:
        if "Failed to launch the browser" in c:
            v = "LAUNCH_FAIL"
        elif "[exit 0]" in c and "Error" not in c:
            v = "EXIT0"
        elif "timed out" in c:
            v = "TIMEOUT"
        else:
            v = "OTHER"
        print(f"  {ca}  task={str(tid)[:8]} idx={idx} {v}")
        if v in ("EXIT0", "OTHER"):
            print("      head:", c[:300].replace("\n", " | "))

    # also count timeouts of mmdc commands (result may lack the Generating line)
    rows2 = conn.execute(text("""
        select m.task_id, m.idx, m.created_at
        from messages m
        join messages a on a.task_id = m.task_id and a.idx = m.idx - 1
        where m.payload->>'role' = 'tool'
          and m.payload->>'content' like '%timed out%'
          and a.payload::text like '%mmdc%'
          and m.created_at > now() - interval '90 days'
        order by m.created_at
    """)).fetchall()
    print(f"\n[MMDC TIMEOUTS last 90d] count={len(rows2)}")
    for tid, idx, ca in rows2:
        print(f"  {ca}  task={str(tid)[:8]} idx={idx}")

    # detail: 06-23 c4f03d56 failure command+error
    print("\n[DETAIL c4f03d56 idx 84-86]")
    rows3 = conn.execute(text("""
        select idx, payload from messages
        where task_id::text like 'c4f03d56%' and idx between 83 and 86 order by idx
    """)).fetchall()
    for idx, p in rows3:
        print(f"[{idx}] {p.get('role')}")
        for tc in p.get("tool_calls") or []:
            fn = tc.get("function") or {}
            print(f"    CALL {fn.get('name')}: {str(fn.get('arguments'))[:600]}")
        if p.get("role") == "tool":
            print(f"    RESULT: {str(p.get('content'))[:1200]}")
