import glob
import json
import re
import sys
from pathlib import Path

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

inbox_dir = Path("docs/design_requests/inbox")
files = sorted(inbox_dir.glob("*.md"))

results = []

for f in files:
    content = f.read_text(encoding="utf-8")
    
    # Metadata fields
    def get_field(pattern, default=""):
        m = re.search(pattern, content)
        return m.group(1).strip() if m else default

    req_id = get_field(r"\*\*Mã Yêu Cầu \(Request ID\)\*\*:\s*`?([A-Za-z0-9_\-]+)`?")
    if not req_id:
        req_id = get_field(r"\*\*ID\*\*:\s*`?([A-Za-z0-9_\-]+)`?", f.stem)
        
    title = get_field(r"\*\*Tên Yêu Cầu \(Title\)\*\*:\s*(.+)")
    dept = get_field(r"\*\*Phòng Ban Khởi Tạo \(Requesting Dept\)\*\*:\s*(.+)")
    source_doc = get_field(r"\*\*Tài Liệu Nguồn Căn Cứ \(Source Document\)\*\*:\s*(.+)")
    category = get_field(r"\*\*Phân Loại Tài Nguyên \(Asset Category\)\*\*:\s*`?([A-Za-z0-9_]+)`?")
    priority = get_field(r"\*\*Mức Độ Ưu Tiên \(Priority\)\*\*:\s*`?([A-Za-z0-9_]+)`?")
    assigned = get_field(r"\*\*Sub-Agent Tiếp Nhận Chỉ Định \(Assigned Subagent\)\*\*:\s*`?([A-Za-z0-9_]+)`?")
    target_path = get_field(r"\*\*Đường Dẫn Mục Tiêu \(Target Path\)\*\*:\s*`?([^`\n]+)`?")
    dimensions = get_field(r"\*\*Kích Thước \(Dimensions\)\*\*:\s*`?([^`\n]+)`?")
    size_budget = get_field(r"\*\*Ngân Sách Dung Lượng \(Size Budget\)\*\*:\s*`?([^`\n]+)`?")
    normal_req = get_field(r"\*\*Yêu Cầu Normal Map \(Normal Map Required\)\*\*:\s*`?([A-Za-z0-9_]+)`?")
    created_date = get_field(r"\*\*Ngày Khởi Tạo \(Created Date\)\*\*:\s*`?([0-9\-]+)`?")
    sla = get_field(r"\*\*Hạn Định Mục Tiêu \(Target SLA\)\*\*:\s*`?([^`\n]+)`?")

    # Deliverables section
    deliv_section = ""
    m_deliv = re.search(r"## 4\. DANH MỤC SẢN PHẨM ĐẦU RA MONG ĐỢI \(DELIVERABLES\)(.*?)(?:## 5\.|\Z)", content, re.DOTALL)
    if m_deliv:
        deliv_section = m_deliv.group(1).strip()
    
    deliverables = []
    for line in deliv_section.splitlines():
        line = line.strip()
        m_item = re.search(r"- \[[ x]\]\s*`?([^`]+)`?", line)
        if m_item:
            deliverables.append(m_item.group(1).strip())
            
    # Technical specs table
    specs = {}
    m_specs = re.search(r"## 3\. THÔNG SỐ KỸ THUẬT CHI TIẾT \(TECHNICAL SPECIFICATIONS\)(.*?)(?:## 4\.|\Z)", content, re.DOTALL)
    if m_specs:
        specs_table = m_specs.group(1).strip()
        for row in specs_table.splitlines():
            row = row.strip()
            if row.startswith("|") and not row.startswith("| :---"):
                parts = [p.strip() for p in row.split("|")[1:-1]]
                if len(parts) >= 2:
                    k = parts[0].replace("**", "").strip()
                    v = parts[1].strip()
                    if k and k != "Tiêu Chí Kỹ Thuật":
                        specs[k] = v

    # Context & Lore
    context_lore = ""
    m_lore = re.search(r"## 2\. BỐI CẢNH NGHIỆP VỤ & CỐT TRUYỆN \(CONTEXT & LORE\)(.*?)(?:## 3\.|\Z)", content, re.DOTALL)
    if m_lore:
        context_lore = m_lore.group(1).strip()

    # Determine emissive, shader, metadata from deliverables and specs
    has_normal_deliv = any("normal" in d.lower() for d in deliverables) or normal_req.upper() == "YES"
    has_emissive_deliv = any("emissive" in d.lower() for d in deliverables) or "emissive" in str(specs).lower()
    has_shader_deliv = any(d.endswith(".metal") for d in deliverables) or "shader" in str(specs).lower() or "metal" in str(specs).lower()
    has_metadata_deliv = any(d.endswith("_metadata.json") or d.endswith(".json") for d in deliverables)

    results.append({
        "file": f.name,
        "req_id": req_id,
        "title": title,
        "dept": dept,
        "source_doc": source_doc,
        "category": category,
        "priority": priority,
        "assigned": assigned,
        "target_path": target_path,
        "dimensions": dimensions,
        "size_budget": size_budget,
        "normal_req": normal_req,
        "created_date": created_date,
        "sla": sla,
        "deliverables": deliverables,
        "specs": specs,
        "context_lore": context_lore,
        "has_normal": has_normal_deliv,
        "has_emissive": has_emissive_deliv,
        "has_shader": has_shader_deliv,
        "has_metadata": has_metadata_deliv,
    })

out_json = Path(".agents/teamwork/spec_miner_survey_1/survey_summary.json")
out_json.write_text(json.dumps(results, indent=2, ensure_ascii=False), encoding="utf-8")
print(f"Parsed {len(results)} DRQ files successfully into {out_json}")
