"""细看几个 can't-open-file 案例的前文: 模型到底写没写过那个 .py 文件。"""
import json
import os
import sys
from pathlib import Path

sys.stdout.reconfigure(encoding="utf-8", errors="replace")

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

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

CASES = [
    ("90c8bba9", 30),   # 最近一条, 相对路径形态
    ("0d7dd9d9", 75),   # 路径重复拼接形态
    ("a395ee0c", 135),  # args 是 code 却报 script 不存在
]

with engine.connect() as conn:
    for tid8, fail_idx in CASES:
        task_id = conn.execute(
            text("select task_id from tasks where task_id::text like :p"),
            {"p": tid8 + "%"},
        ).scalar()
        print("=" * 100)
        print(f"TASK {tid8} fail_idx={fail_idx}")
        msgs = conn.execute(
            text("select idx, payload from messages where task_id=:t and idx <= :i order by idx"),
            {"t": task_id, "i": fail_idx + 1},
        ).fetchall()
        for idx, p in msgs:
            role = p.get("role")
            if role == "assistant":
                tcs = p.get("tool_calls") or []
                for tc in tcs:
                    fn = tc.get("function") or {}
                    args = fn.get("arguments") or ""
                    print(f"  #{idx} A> {fn.get('name')} {args[:180]}")
                if not tcs:
                    c = p.get("content") or ""
                    if isinstance(c, list):
                        c = json.dumps(c, ensure_ascii=False)
                    print(f"  #{idx} A(text)> {c[:150]}")
            elif role == "tool":
                c = p.get("content") or ""
                if isinstance(c, list):
                    c = json.dumps(c, ensure_ascii=False)
                name = p.get("name")
                flat = " | ".join(c.strip().splitlines()[:2])
                print(f"  #{idx} T< [{name}] {flat[:180]}")
            elif role == "user":
                c = p.get("content") or ""
                if isinstance(c, list):
                    c = json.dumps(c, ensure_ascii=False)
                print(f"  #{idx} U> {c[:120]}")
        print()
