from __future__ import annotations

from pathlib import Path
import json
import re

ROOT = Path(__file__).resolve().parents[1]
REVIEW_DIR = ROOT / "review"
OUT_DIR = ROOT / "approved-memory"

DECISION_RE = re.compile(r"\*\*Review decision:\*\* `([^`]+)`")
FIELD_RE = re.compile(r"\*\*([^*]+):\*\* `?([^`\n]+)`?")
CANDIDATE_RE = re.compile(r"^### \d+\. `([^`]+)`", re.M)


def parse_sections(text: str):
    matches = list(CANDIDATE_RE.finditer(text))
    for i, m in enumerate(matches):
        start = m.start()
        end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
        yield m.group(1), text[start:end]


def extract_code_preview(section: str) -> str:
    m = re.search(r"\*\*Candidate content preview\*\*\s+```text\n(.*?)\n```", section, re.S)
    return m.group(1).strip() if m else ""


def parse_candidate(candidate_id: str, section: str, packet: Path) -> dict:
    decision_match = DECISION_RE.search(section)
    decision = (decision_match.group(1).strip().upper() if decision_match else "PENDING")
    fields = {k.strip().lower().replace(" ", "_"): v.strip() for k, v in FIELD_RE.findall(section)}
    content = extract_code_preview(section)
    return {
        "candidate_id": candidate_id,
        "packet": str(packet.relative_to(ROOT)),
        "decision": decision,
        "content": content,
        "metadata": {
            "memory_type": fields.get("recommended_type"),
            "sensitivity": fields.get("recommended_sensitivity"),
            "matched_query": fields.get("matched_query"),
            "source_title": fields.get("source"),
            "source_raw_path": fields.get("raw_path"),
            "source_conversation_id": fields.get("conversation"),
            "source_chunk_id": fields.get("chunk"),
            "source_message_range": fields.get("message_range"),
            "review_status": decision.lower(),
            "created_from": "bert_review_packet",
        },
    }


def main() -> int:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    buckets = {
        "APPROVE": [],
        "SOURCE_ONLY": [],
        "REJECT": [],
        "EDIT": [],
        "PENDING": [],
    }
    for packet in sorted(REVIEW_DIR.glob("*-memory-candidates.md")):
        text = packet.read_text(encoding="utf-8")
        for cid, section in parse_sections(text):
            c = parse_candidate(cid, section, packet)
            buckets.setdefault(c["decision"], []).append(c)

    mapping = {
        "APPROVE": "approved-memories.jsonl",
        "SOURCE_ONLY": "source-only-index.jsonl",
        "REJECT": "rejected-memory-log.jsonl",
        "EDIT": "needs-edit-memory-candidates.jsonl",
        "PENDING": "pending-memory-candidates.jsonl",
    }
    for decision, filename in mapping.items():
        out = OUT_DIR / filename
        with out.open("w", encoding="utf-8") as fh:
            for item in buckets.get(decision, []):
                fh.write(json.dumps(item, ensure_ascii=False) + "\n")
        print(f"{decision}: {len(buckets.get(decision, []))} -> {out}")
    return 0


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