"""拉 edit/write malformed 的原始损坏参数样本,判断是「两调用拼接」还是「截断」。"""
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():
    s = line.strip()
    if s.startswith("ZCBOT_DB_URL=") and not s.startswith("#"):
        os.environ["ZCBOT_DB_URL"] = s.split("=", 1)[1].strip()
from sqlalchemy import create_engine, text  # noqa: E402

tool = sys.argv[1] if len(sys.argv) > 1 else "edit"
eng = create_engine(os.environ["ZCBOT_DB_URL"])
with eng.connect() as c:
    rows = c.execute(text(
        "select task_id, model_profile, units->>'err' err, "
        "units->>'head' head, units->>'tail' tail "
        "from usage_events "
        "where kind='tool_malformed' and units->>'tool'=:t "
        "and created_at >= now() - interval '7 days' "
        "order by created_at desc limit 8"
    ), {"t": tool}).fetchall()

for i, (tid, mp, err, head, tail) in enumerate(rows, 1):
    print(f"\n=== {i}  task={str(tid)[:8]}  model={mp} ===")
    print(f"  err : {err}")
    print(f"  head: {(head or '')[:220]}")
    print(f"  tail: {(tail or '')[-220:]}")
