"""Phase 6C: Cultural Synthesis — monthly distillation of team principles."""
import json
from datetime import datetime, timezone
from pathlib import Path
from pulse.core.paths import get_state_dir, get_brain_dir
from pulse.core.brain_db import get_conn
from pulse.core import event_bus

CULTURE_DIR = get_brain_dir() / "Culture"
PRINCIPLES_FILE = CULTURE_DIR / "principles.json"


def run_culture_synthesis(verbose=False) -> dict:
    """
    Monthly distillation of top lessons + patterns -> 5 core principles.
    Uses LLM if available, frequency-based fallback otherwise.
    """
    conn = get_conn()

    # Get top 50 lessons + top 30 patterns by salience*confidence
    lessons = conn.execute("""
        SELECT content, title, domain, salience, confidence
        FROM lessons WHERE validity = 'valid'
        ORDER BY salience * confidence DESC LIMIT 50
    """).fetchall()

    patterns = conn.execute("""
        SELECT content, title, domain, salience, confidence
        FROM patterns WHERE validity = 'valid'
        ORDER BY salience * confidence DESC LIMIT 30
    """).fetchall()

    all_items = [dict(r) for r in lessons] + [dict(r) for r in patterns]

    if len(all_items) < 10:
        return {"status": "insufficient_data", "items": len(all_items)}

    # Try LLM distillation
    principles = _llm_distill(all_items)
    if not principles:
        principles = _frequency_distill(all_items)

    # Save principles
    result = {
        "distilled_date": datetime.now(timezone.utc).isoformat(),
        "principles": principles,
        "source_count": len(all_items),
    }

    CULTURE_DIR.mkdir(parents=True, exist_ok=True)
    PRINCIPLES_FILE.write_text(json.dumps(result, indent=2), encoding="utf-8")

    if verbose:
        print(f"  [CULTURE] Distilled {len(principles)} principles from {len(all_items)} items")

    event_bus.publish("culture.synthesized", "culture_synth", {"principles": len(principles)})
    return result


def _llm_distill(items: list) -> list:
    """Use LLM to extract 5 core principles."""
    try:
        from pulse.core.llm_router import dispatch
        content = "\n".join(
            f"- [{i.get('domain', 'general')}] {i.get('title', '')[:80]}: {i.get('content', '')[:120]}"
            for i in items[:40]
        )
        prompt = (
            f"Read these {len(items[:40])} engineering lessons and patterns. "
            f"What are the 5 most important principles that emerge? "
            f"Reply as JSON array: [{{\"rank\": 1, \"title\": \"...\", \"description\": \"...\", \"confidence\": 0.0-1.0}}]"
            f"\n\n{content}"
        )
        result = dispatch(prompt, task_type="fast")
        # Extract JSON from response
        start = result.find("[")
        end = result.rfind("]") + 1
        if start >= 0 and end > start:
            return json.loads(result[start:end])[:5]
    except Exception:
        pass
    return []


def _frequency_distill(items: list) -> list:
    """Fallback: frequency-based principle extraction."""
    from collections import Counter
    words = Counter()
    stop = {
        "the", "a", "an", "is", "was", "are", "were", "to", "from",
        "in", "on", "of", "and", "or", "for", "with", "not", "this",
        "that", "it",
    }
    for item in items:
        text = f"{item.get('title', '')} {item.get('content', '')}".lower()
        for word in text.split():
            if len(word) > 3 and word not in stop:
                words[word] += 1

    principles = []
    for rank, (word, count) in enumerate(words.most_common(5), 1):
        principles.append({
            "rank": rank, "title": word.capitalize(),
            "description": f"Recurring theme ({count} mentions across {len(items)} items)",
            "confidence": min(1.0, count / len(items)),
        })
    return principles


def load_principles() -> list:
    """Load current principles for boot injection."""
    if not PRINCIPLES_FILE.exists():
        return []
    try:
        data = json.loads(PRINCIPLES_FILE.read_text(encoding="utf-8"))
        return data.get("principles", [])
    except Exception:
        return []
