"""Output formatters — JSON, Markdown, CLAUDE.md, USER.md."""

from __future__ import annotations

import json

from syke.models import UserProfile


def format_profile(profile: UserProfile, fmt: str) -> str:
    """Format a profile for output."""
    formatters = {
        "json": _format_json,
        "markdown": _format_markdown,
        "claude-md": _format_claude_md,
        "user-md": _format_user_md,
    }
    formatter = formatters.get(fmt)
    if not formatter:
        raise ValueError(f"Unknown format: {fmt}. Choose from: {', '.join(formatters)}")
    return formatter(profile)


def _format_json(profile: UserProfile) -> str:
    return profile.model_dump_json(indent=2)


def _format_markdown(profile: UserProfile) -> str:
    lines = [
        f"# {profile.user_id} — Syke Profile",
        f"*Generated {profile.created_at.strftime('%Y-%m-%d %H:%M')} from {', '.join(profile.sources)} ({profile.events_count} events)*\n",
        "## Who They Are",
        profile.identity_anchor,
        "",
        "## Active Threads",
    ]

    for t in profile.active_threads:
        lines.append(f"### {t.name} [{t.intensity}]")
        lines.append(t.description)
        if t.platforms:
            lines.append(f"*Seen on: {', '.join(t.platforms)}*")
        if t.recent_signals:
            lines.append("Recent signals:")
            for s in t.recent_signals:
                lines.append(f"- {s}")
        lines.append("")

    lines.extend([
        "## Recent Context",
        profile.recent_detail,
        "",
        "## Background",
        profile.background_context,
    ])

    if profile.world_state:
        lines.extend(["", "## World State", profile.world_state])

    if profile.voice_patterns:
        vp = profile.voice_patterns
        lines.extend([
            "",
            "## Voice & Communication",
            f"**Tone**: {vp.tone}",
            f"**Style**: {vp.communication_style}",
        ])
        if vp.vocabulary_notes:
            lines.append("**Vocabulary**: " + ", ".join(vp.vocabulary_notes))
        if vp.examples:
            lines.append("\n**Examples**:")
            for ex in vp.examples:
                lines.append(f"> {ex}")

    return "\n".join(lines)


def _format_claude_md(profile: UserProfile) -> str:
    """Format as CLAUDE.md context injection."""
    lines = [
        f"# About {profile.user_id}",
        f"<!-- Generated by Syke from {', '.join(profile.sources)} ({profile.events_count} events) -->",
        "",
        profile.identity_anchor,
        "",
        "## What's Active Right Now",
    ]

    for t in profile.active_threads:
        intensity_marker = {"high": "🔥", "medium": "→", "low": "·"}.get(t.intensity, "→")
        lines.append(f"{intensity_marker} **{t.name}**: {t.description}")
        if t.recent_signals:
            for s in t.recent_signals[:2]:
                lines.append(f"  - {s}")

    lines.extend([
        "",
        "## Recent Context",
        profile.recent_detail,
        "",
        "## Background",
        profile.background_context,
    ])

    if profile.world_state:
        lines.extend(["", "## Current World State", profile.world_state])

    if profile.voice_patterns:
        vp = profile.voice_patterns
        lines.extend([
            "",
            "## How They Communicate",
            f"{vp.tone}. {vp.communication_style}",
        ])

    return "\n".join(lines)


def _format_user_md(profile: UserProfile) -> str:
    """Format as USER.md for external platform consumption."""
    lines = [
        f"# User Profile: {profile.user_id}",
        f"<!-- Syke perception | {', '.join(profile.sources)} | {profile.events_count} events -->",
        "",
        "## Identity",
        profile.identity_anchor,
        "",
        "## Current Focus",
    ]

    for t in profile.active_threads:
        if t.intensity in ("high", "medium"):
            lines.append(f"- **{t.name}**: {t.description}")

    lines.extend([
        "",
        "## Context",
        profile.recent_detail,
    ])

    if profile.world_state:
        lines.extend(["", "## Current State", profile.world_state])

    lines.extend([
        "",
        "## Communication Preferences",
    ])

    if profile.voice_patterns:
        vp = profile.voice_patterns
        lines.append(f"Tone: {vp.tone}")
        lines.append(f"Style: {vp.communication_style}")

    return "\n".join(lines)
