"""CLAUDE.md seeder for Memory Nexus MCP server.

On first connection to a new project, reads CLAUDE.md and parses
it into structured observations for batch write_back.

Dedup is handled server-side (core/store.py cosine >= 0.95).
"""

import hashlib
import re
from pathlib import Path
from typing import Optional


def _classify_section(heading: str, body: str) -> tuple[str, str]:
    """Classify a CLAUDE.md section into event_type and drawer hint.

    Returns (event_type, drawer_hint).
    """
    h = heading.lower()

    # Build/run/deploy commands => directives
    if any(kw in h for kw in ["command", "build", "run", "install", "deploy", "test"]):
        return "directive_set", "workflow"

    # Architecture/structure/design => knowledge facts
    if any(kw in h for kw in ["architecture", "structure", "design", "pattern", "api", "endpoint"]):
        return "observation", "architecture"

    # Style/convention/preference => preferences
    if any(kw in h for kw in ["style", "convention", "preference", "rule", "security"]):
        return "observation", "preferences"

    # Environment/config => knowledge
    if any(kw in h for kw in ["environment", "variable", "config", "deploy", "secret"]):
        return "observation", "knowledge"

    # Default
    return "observation", "knowledge"


def parse_claude_md(cwd: str = ".") -> Optional[list[dict]]:
    """Parse CLAUDE.md into structured writeback events.

    Returns list of event dicts compatible with /v1/hats/{id}/writeback/batch,
    or None if no CLAUDE.md found.
    """
    claude_md = Path(cwd) / "CLAUDE.md"
    if not claude_md.exists():
        return None

    try:
        content = claude_md.read_text(encoding="utf-8")
    except OSError:
        return None

    if not content.strip():
        return None

    events = []
    sections = re.split(r"^## ", content, flags=re.MULTILINE)

    for section in sections:
        section = section.strip()
        if not section:
            continue

        lines = section.split("\n", 1)
        heading = lines[0].strip().rstrip("#").strip()
        body = lines[1].strip() if len(lines) > 1 else section

        if not body or len(body) < 20:
            continue

        event_type, drawer = _classify_section(heading, body)

        # Truncate very long sections
        if len(body) > 2000:
            body = body[:2000] + "..."

        event = {
            "event_type": event_type,
            "content": f"[CLAUDE.md: {heading}] {body}" if heading else body,
            "drawer": drawer,
        }

        # Add directive-specific fields
        if event_type == "directive_set":
            event["directive_id"] = f"seed_{hashlib.sha256(heading.encode()).hexdigest()[:8]}"
            event["priority"] = 70

        events.append(event)

    return events if events else None
