#!/usr/bin/env python3
"""Exporta transcript Cursor → CHAT_BRUTO (ligbox-ops-platform + canais Obsidian/LAPTOP)."""

import importlib.util
import shutil
import sys
from datetime import datetime
from pathlib import Path

_spec = importlib.util.spec_from_file_location(
    "export_ibytera",
    "/root/obsidian-infra/carbonio/ibytera-mail-portal/LAPTOP/scripts/export-chat-bruto.py",
)
_mod = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_mod)
convert = _mod.convert


def main() -> int:
    if len(sys.argv) < 4:
        print(
            "Uso: export-chat-bruto.py <jsonl_src> <base_name> <transcript_id>",
            file=sys.stderr,
        )
        return 1

    jsonl_src = Path(sys.argv[1])
    base = sys.argv[2]
    transcript_id = sys.argv[3]
    project_root = Path(__file__).resolve().parents[1]

    channels = [
        project_root / "chat-bruto",
        Path("/root/obsidian-infra/ligbox-ops-platform/chat-bruto"),
        project_root / "LAPTOP",
        Path("/root/obsidian-infra/ligbox-ops-platform/LAPTOP"),
        Path("/root/obsidian-infra/carbonio/ibytera-mail-portal/LAPTOP"),
    ]

    meta = {
        "title": f"CHAT BRUTO — {base}",
        "transcript_id": transcript_id,
        "project": "ligbox-ops-platform / VM122 / Spec Kit",
        "date": datetime.now().strftime("%Y-%m-%d"),
        "description": (
            "Ligbox Ops Platform: VM122, Support Desk, Spec Kit, integrações VM112/Wazuh. "
            "Texto integral (user + assistant + ferramentas)."
        ),
    }

    tmp_txt = project_root / "chat-bruto" / f"{base}.txt"
    tmp_txt.parent.mkdir(parents=True, exist_ok=True)
    count = convert(jsonl_src, tmp_txt, meta)

    for ch in channels:
        ch.mkdir(parents=True, exist_ok=True)
        dst_txt = ch / f"{base}.txt"
        if dst_txt.resolve() != tmp_txt.resolve():
            shutil.copy2(tmp_txt, dst_txt)
        dst_jsonl = ch / f"{base}.jsonl"
        if dst_jsonl.resolve() != jsonl_src.resolve():
            shutil.copy2(jsonl_src, dst_jsonl)

    print(f"OK: {count} mensagens → {base}.txt ({len(channels)} canais)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
