#!/usr/bin/env python3
"""
RFC/W3C 문서 임시파일 복사 스크립트
web_fetch로 다운로드된 임시파일들을 references 디렉토리로 복사합니다.
"""
import os
import shutil
import glob

TEMP_BASE = "/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/claude-hostloop-plugins/b8db1e6c7fa308f5/projects/-Users-godopu16-Library-Application-Support-Claude-local-agent-mode-sessions-d296e3e8-b0b5-4f4f-bb64-8c0d840bb199-297e4cfe-e248-44e9-8c1d-151efb5c1d9c-local-0a2efad5-ff3c-41a8-bf0b-eefa704c64ee-output-l5mtkv/70a71999-c1c1-4c50-bb5d-1ed02fe6f250/tool-results"

DEST_DIR = os.path.dirname(os.path.abspath(__file__))

FILES_MAP = {
    "mcp-workspace-web_fetch-1780816591394.txt": "RFC9000_QUIC_Transport.txt",
    "mcp-workspace-web_fetch-1780816603173.txt": "RFC7252_CoAP.txt",
    "mcp-workspace-web_fetch-1780816606749.txt": "RFC8949_CBOR.txt",
    "mcp-workspace-web_fetch-1780816616243.txt": "RFC9114_HTTP3.txt",
    "mcp-workspace-web_fetch-1780816619718.txt": "RFC8446_TLS13.txt",
    "toolu_01BFYbhdAjbXPLctFLnGVDP6.json": "W3C_TraceContext_Spec.html",
}

os.makedirs(DEST_DIR, exist_ok=True)

for src_fname, dest_fname in FILES_MAP.items():
    src_path = os.path.join(TEMP_BASE, src_fname)
    dest_path = os.path.join(DEST_DIR, dest_fname)
    if os.path.exists(src_path):
        if dest_fname.endswith(".html"):
            # JSON wrapper에서 text 추출
            import json
            with open(src_path, "r", encoding="utf-8") as f:
                raw = f.read()
            try:
                data = json.loads(raw)
                if isinstance(data, list) and data and "text" in data[0]:
                    content = data[0]["text"]
                    # header 라인 제거 (첫 4줄: URL, redirect, content-type, blank)
                    lines = content.split("\n")
                    start = 0
                    for i, ln in enumerate(lines[:10]):
                        if ln.startswith("Content-Type:") or ln.startswith("→"):
                            start = i + 2
                    with open(dest_path, "w", encoding="utf-8") as f:
                        f.write("\n".join(lines[start:]))
                    size = os.path.getsize(dest_path)
                    print(f"OK  {dest_fname}  ({size:,} bytes)")
                else:
                    shutil.copy2(src_path, dest_path)
                    size = os.path.getsize(dest_path)
                    print(f"OK (raw copy)  {dest_fname}  ({size:,} bytes)")
            except Exception as e:
                shutil.copy2(src_path, dest_path)
                size = os.path.getsize(dest_path)
                print(f"OK (fallback copy)  {dest_fname}  ({size:,} bytes) [{e}]")
        else:
            # Plain text: strip header lines (URL, redirect, content-type)
            with open(src_path, "r", encoding="utf-8", errors="replace") as f:
                lines = f.readlines()
            # Skip first few lines that are metadata added by web_fetch
            start = 0
            for i, ln in enumerate(lines[:6]):
                stripped = ln.strip()
                if stripped.startswith("https://") or stripped.startswith("→") or stripped.startswith("Content-Type:"):
                    start = i + 1
            with open(dest_path, "w", encoding="utf-8") as f:
                f.writelines(lines[start:])
            size = os.path.getsize(dest_path)
            print(f"OK  {dest_fname}  ({size:,} bytes)")
    else:
        print(f"MISSING: {src_path}")

print("\nDone. Files in references:")
for f in sorted(os.listdir(DEST_DIR)):
    if not f.startswith("_"):
        path = os.path.join(DEST_DIR, f)
        size = os.path.getsize(path)
        print(f"  {f}  ({size:,} bytes)")
