"""Dump task 2a1bc25d full row + messages (ASCII safe, prefix match on task_id)."""
import json
import os
import sys
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 / "_task_2a1bc25d.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"])
PREFIX = "2a1bc25d"


def s(x, n=4000):
    t = str(x or "")
    return t if len(t) <= n else t[:n] + f"...[+{len(t)-n} chars]"


with engine.connect() as conn:
    row = conn.execute(
        text("select * from tasks where task_id::text like :p"), {"p": PREFIX + "%"}
    ).mappings().fetchone()
    if not row:
        print("[NO TASK]", PREFIX)
        sys.exit(1)
    TID = row["task_id"]
    print("[TASK ROW]")
    for k, v in dict(row).items():
        print(f"  {k} = {s(v, 2000)}")

    msgs = conn.execute(
        text("select idx,payload,model_profile,tokens_in,tokens_out,created_at from messages "
             "where task_id=:t order by idx"),
        {"t": TID},
    ).fetchall()
    print(f"\n[MESSAGES] count={len(msgs)}\n")
    for idx, p, mp, ti, to, ca in msgs:
        if isinstance(p, str):
            try:
                p = json.loads(p)
            except Exception as e:
                print(f"[{idx}] !! payload JSON parse fail: {e}; raw head: {s(p, 500)}")
                continue
        role = p.get("role")
        head = f"[{idx}] {role}"
        if mp:
            head += f" ({mp})"
        if ti or to:
            head += f" tok={ti}/{to}"
        head += f" at={ca}"
        print(head)
        content = p.get("content")
        if content is not None:
            print("    content:", s(content, 2000))
        for tc in p.get("tool_calls") or []:
            fn = tc.get("function") or {}
            print(f"    CALL {fn.get('name')}({s(fn.get('arguments'), 800)})")
        if role == "tool":
            print(f"    TOOL[{p.get('name')}] id={p.get('tool_call_id')}:", s(content, 1200))
        print()
