"""Inspect the single OK mmdc render (task 839a7c14 idx~112) vs a failing neighbor. (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_ok_case.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 idx, payload from messages
        where task_id::text like '839a7c14%' and idx between 105 and 118
        order by idx
    """)).fetchall()
    for idx, p in rows:
        role = p.get("role")
        print(f"[{idx}] {role}")
        for tc in p.get("tool_calls") or []:
            fn = tc.get("function") or {}
            print(f"    CALL {fn.get('name')}: {str(fn.get('arguments'))[:800]}")
        if role == "tool":
            print(f"    RESULT: {str(p.get('content'))[:800]}")
        print()
