#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Plans Digestion: Extracts DECISIONS and PRIORITIES from Personal_Plans/
into Hippocampus strategic intents. Agents see distilled strategy without
reading 166K of planning docs.

Run manually or as a periodic task. Not a daemon.
Dependencies: Python stdlib only (Law 4)
"""
import json
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent.parent

# When run directly, ensure pulse package is importable
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from pulse.core.brain_utils import save_json, HIPPOCAMPUS_DIR

PLANS_DIR = ROOT_DIR / "Personal_Plans"
OUTPUT_FILE = HIPPOCAMPUS_DIR / "Intents" / "strategic_intents.json"

# Patterns that signal decisions and priorities in markdown
DECISION_PATTERNS = [
    re.compile(r'(?i)\*\*(?:key )?decision[s]?[:\*]*\*?\*?\s*(.+)'),
    re.compile(r'(?i)- \[x\]\s+\*\*(.+?)\*\*'),  # Checked items with bold
    re.compile(r'(?i)(?:priority|immediate|critical|first|urgent)[:\s]+(.+)', re.IGNORECASE),
]

STATUS_PATTERNS = {
    "done": re.compile(r'(?i)\b(?:DONE|COMPLETE[D]?|FIXED|RESOLVED|EXECUTED|✅)\b'),
    "in_progress": re.compile(r'(?i)\b(?:IN PROGRESS|ACTIVE|CURRENT|🔄)\b'),
    "pending": re.compile(r'(?i)\b(?:PENDING|TODO|UPCOMING|PLANNED|⏳)\b'),
}

PHASE_PATTERN = re.compile(r'(?i)##\s+.*?phase\s+(\d+|[A-D])[:\s]+(.+)')


def _extract_intents_from_file(path: Path) -> list[dict]:
    """Extract strategic intents from a single markdown/text file."""
    try:
        text = path.read_text(encoding="utf-8", errors="replace")
    except OSError:
        return []

    intents = []
    lines = text.splitlines()
    current_section = ""

    for line in lines:
        stripped = line.strip()

        # Track current section
        if stripped.startswith("## "):
            current_section = stripped[3:].strip()

        # Extract phase information
        phase_match = PHASE_PATTERN.match(stripped)
        if phase_match:
            phase_id = phase_match.group(1)
            phase_title = phase_match.group(2).strip()

            # Determine status
            status = "pending"
            for s, pat in STATUS_PATTERNS.items():
                if pat.search(stripped):
                    status = s
                    break

            intents.append({
                "type": "phase",
                "phase": phase_id,
                "title": phase_title,
                "status": status,
                "source": path.name,
            })
            continue

        # Extract decisions
        for pat in DECISION_PATTERNS:
            match = pat.search(stripped)
            if match:
                decision_text = match.group(1).strip().rstrip("*").strip()
                if len(decision_text) > 10:  # Skip tiny fragments
                    status = "pending"
                    for s, spat in STATUS_PATTERNS.items():
                        if spat.search(stripped) or spat.search(decision_text):
                            status = s
                            break

                    intents.append({
                        "type": "decision",
                        "text": decision_text[:200],
                        "status": status,
                        "section": current_section[:100],
                        "source": path.name,
                    })
                break  # Only match first pattern per line

    return intents


def _extract_market_priorities(text: str, source: str) -> list[dict]:
    """Extract market/business priorities from text."""
    intents = []
    priority_triggers = [
        (r'(?i)healthcare\s+first', "Healthcare is first market entry ($50B TAM)"),
        (r'(?i)enterprise\s+(?:second|scaling)', "Enterprise is second market (after healthcare)"),
        (r'(?i)\$(\d+[MBK])\s+(?:for|over)\s+(\d+)\s*months?', None),  # Dynamic
        (r'(?i)monetiz(?:e|ation)', "Monetization strategy needed"),
    ]

    for pattern, default_text in priority_triggers:
        match = re.search(pattern, text)
        if match:
            if default_text:
                intents.append({
                    "type": "priority",
                    "text": default_text,
                    "source": source,
                })
            else:
                intents.append({
                    "type": "priority",
                    "text": f"Budget: ${match.group(1)} for {match.group(2)} months",
                    "source": source,
                })
    return intents


def synthesize():
    """Main synthesis: scan Personal_Plans/, extract intents, write output."""
    if not PLANS_DIR.exists():
        print("[PLANS] Personal_Plans/ not found. Skipping.")
        return

    all_intents = []
    files_scanned = 0

    for md_file in sorted(PLANS_DIR.rglob("*.md")):
        intents = _extract_intents_from_file(md_file)
        all_intents.extend(intents)
        files_scanned += 1

    for txt_file in sorted(PLANS_DIR.rglob("*.txt")):
        try:
            text = txt_file.read_text(encoding="utf-8", errors="replace")
            market = _extract_market_priorities(text, txt_file.name)
            all_intents.extend(market)
            files_scanned += 1
        except OSError:
            continue

    # Deduplicate by text similarity
    seen_texts = set()
    unique_intents = []
    for intent in all_intents:
        key = intent.get("text", intent.get("title", ""))[:50].lower()
        if key not in seen_texts:
            seen_texts.add(key)
            unique_intents.append(intent)

    # Sort: priorities first, then phases, then decisions
    type_order = {"priority": 0, "phase": 1, "decision": 2}
    unique_intents.sort(key=lambda x: type_order.get(x["type"], 9))

    output = {
        "synthesized_at": datetime.now(timezone.utc).isoformat(),
        "files_scanned": files_scanned,
        "intent_count": len(unique_intents),
        "intents": unique_intents,
    }

    save_json(OUTPUT_FILE, output)
    print(f"[PLANS] Synthesized {len(unique_intents)} strategic intents "
          f"from {files_scanned} files -> {OUTPUT_FILE.name}")

    # Print summary
    by_type = {}
    for i in unique_intents:
        by_type.setdefault(i["type"], []).append(i)

    for t, items in by_type.items():
        print(f"  {t}: {len(items)} items")
        for item in items[:3]:
            text = item.get("text", item.get("title", "?"))
            status = item.get("status", "")
            print(f"    - [{status}] {text[:80]}")


if __name__ == "__main__":
    synthesize()
