"""
aura.exporters.claude_code — Export context packs as CLAUDE.md / AGENTS.md sections.

Produces markdown sections that can be appended to CLAUDE.md (for Claude Code
and gstack) or AGENTS.md (for Codex and other agent frameworks).

These files tell AI coding agents WHO the developer is — complementing the
project-level context they already read from the codebase.

Usage:
    aura export developer -f claude-md           # stdout
    aura export developer -f claude-md -o .      # appends to ./CLAUDE.md
    aura export developer,work -f agents-md      # AGENTS.md format
"""

from __future__ import annotations

from aura.schema import SCHEMA_VERSION, ContextPack


def export_claude_md(packs: list[ContextPack]) -> str:
    """
    Export context packs as a CLAUDE.md section.

    Produces a markdown block designed to be appended to a project's CLAUDE.md.
    Claude Code and gstack read this file to understand the developer.

    Args:
        packs: Context packs to include

    Returns:
        Markdown string for CLAUDE.md
    """
    lines: list[str] = []
    lines.append(f"## Developer Identity (aura v{SCHEMA_VERSION})")
    lines.append("")
    lines.append("<!-- Generated by aura-ctx — https://github.com/WozGeek/aura-ctx -->")
    lines.append("<!-- This section describes the developer, not the project. -->")
    lines.append("")

    for pack in packs:
        lines.append(f"### {pack.name} ({pack.scope})")
        if pack.meta.description:
            lines.append(f"_{pack.meta.description}_")
        lines.append("")

        # Identity and role facts first
        identity_facts = [f for f in pack.facts if f.type.value == "identity"]
        skill_facts = [f for f in pack.facts if f.type.value == "skill"]
        pref_facts = [f for f in pack.facts if f.type.value == "preference"]
        style_facts = [f for f in pack.facts if f.type.value == "style"]
        other_facts = [f for f in pack.facts if f.type.value not in ("identity", "skill", "preference", "style")]

        if identity_facts:
            for fact in identity_facts:
                val = fact.value if isinstance(fact.value, str) else ", ".join(fact.value)
                lines.append(f"- **{fact.key}**: {val}")
            lines.append("")

        if skill_facts:
            lines.append("**Stack:**")
            for fact in skill_facts:
                val = fact.value if isinstance(fact.value, str) else ", ".join(fact.value)
                lines.append(f"- {fact.key}: {val}")
            lines.append("")

        if pref_facts:
            lines.append("**Preferences:**")
            for fact in pref_facts:
                val = fact.value if isinstance(fact.value, str) else ", ".join(fact.value)
                lines.append(f"- {fact.key}: {val}")
            lines.append("")

        if style_facts:
            lines.append("**Style:**")
            for fact in style_facts:
                val = fact.value if isinstance(fact.value, str) else ", ".join(fact.value)
                lines.append(f"- {fact.key}: {val}")
            lines.append("")

        if other_facts:
            for fact in other_facts:
                val = fact.value if isinstance(fact.value, str) else ", ".join(fact.value)
                lines.append(f"- {fact.key}: {val}")
            lines.append("")

        if pack.rules:
            lines.append("**Rules** (sorted by priority):")
            for rule in sorted(pack.rules, key=lambda r: -r.priority):
                prefix = f"[P{rule.priority}] " if rule.priority > 0 else ""
                lines.append(f"- {prefix}{rule.instruction}")
            lines.append("")

    # MCP connection note
    lines.append("---")
    lines.append("_aura MCP server runs on `localhost:3847`. For live context, add to your MCP config:_")
    lines.append('```json')
    lines.append('{ "mcpServers": { "aura": { "url": "http://localhost:3847/mcp" } } }')
    lines.append('```')

    return "\n".join(lines) + "\n"


def export_agents_md(packs: list[ContextPack]) -> str:
    """
    Export context packs as an AGENTS.md section.

    Produces a markdown block compatible with Codex, OpenClaw, and other
    agent frameworks that read AGENTS.md for developer context.

    Args:
        packs: Context packs to include

    Returns:
        Markdown string for AGENTS.md
    """
    lines: list[str] = []
    lines.append(f"## Developer Identity (aura v{SCHEMA_VERSION})")
    lines.append("")
    lines.append("<!-- Generated by aura-ctx — https://github.com/WozGeek/aura-ctx -->")
    lines.append("")

    # Flatten all packs into a single developer profile
    all_identity: list[str] = []
    all_stack: list[str] = []
    all_prefs: list[str] = []
    all_rules: list[str] = []

    for pack in packs:
        for fact in pack.facts:
            val = fact.value if isinstance(fact.value, str) else ", ".join(fact.value)
            entry = f"{fact.key}: {val}"
            if fact.type.value == "identity":
                all_identity.append(entry)
            elif fact.type.value in ("skill",):
                all_stack.append(entry)
            elif fact.type.value in ("preference", "style"):
                all_prefs.append(entry)
            else:
                all_prefs.append(entry)

        for rule in sorted(pack.rules, key=lambda r: -r.priority):
            prefix = f"[P{rule.priority}] " if rule.priority > 0 else ""
            all_rules.append(f"{prefix}{rule.instruction}")

    if all_identity:
        lines.append("**Identity:**")
        for item in all_identity:
            lines.append(f"- {item}")
        lines.append("")

    if all_stack:
        lines.append("**Stack:**")
        for item in all_stack:
            lines.append(f"- {item}")
        lines.append("")

    if all_prefs:
        lines.append("**Preferences:**")
        for item in all_prefs:
            lines.append(f"- {item}")
        lines.append("")

    if all_rules:
        lines.append("**Rules:**")
        for item in all_rules:
            lines.append(f"- {item}")
        lines.append("")

    return "\n".join(lines) + "\n"
