#!/usr/bin/env python3
"""
AutoGen + MQTT PDF 임시파일 복사 스크립트
web_fetch로 추출된 임시파일들을 references 디렉토리로 복사합니다.
"""
import os
import shutil

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__))

# Temp file names from the web_fetch calls made in this session
FILES_MAP = {
    "mcp-workspace-web_fetch-1780816592169.txt": "Wu2023_AutoGen_MultiAgent.pdf",
    "mcp-workspace-web_fetch-1780816642475.txt": "MQTT_v5_OASIS_Standard.pdf",
}

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):
        # Plain text extracted from PDF — strip web_fetch header lines
        with open(src_path, "r", encoding="utf-8", errors="replace") as f:
            lines = f.readlines()
        # Skip first few metadata lines added by web_fetch (URL, redirect, content-type, blank)
        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
        # Skip trailing blank line after headers
        if start < len(lines) and lines[start].strip() == "":
            start += 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("\nAll files in references/:")
for fname in sorted(os.listdir(DEST_DIR)):
    if fname.startswith("_"):
        continue
    path = os.path.join(DEST_DIR, fname)
    size = os.path.getsize(path)
    print(f"  {fname}  ({size:,} bytes)")
