"""
Markdown formatter for session context.

Converts SessionContext to Claude-readable markdown.
"""

from lightwave.context.context_models import SessionContext


def format_session_context(context: SessionContext) -> str:
    """Format session context as markdown for Claude Code consumption.

    Args:
        context: SessionContext to format

    Returns:
        Markdown-formatted string
    """
    sections = []

    # Header
    sections.append("# Session Context")
    sections.append("")
    sections.append(f"**Generated**: {context.timestamp.isoformat()}")
    sections.append("")

    # Git Context
    sections.append("## Git Context")
    sections.append("")
    sections.append(f"- **Repository**: {context.git.repo}")
    sections.append(f"- **Branch**: `{context.git.branch}`")
    sections.append(f"- **Clean**: {'✓ Yes' if context.git.is_clean else '✗ No (uncommitted changes)'}")

    if context.git.task_id_from_branch:
        sections.append(f"- **Task ID (from branch)**: `{context.git.task_id_from_branch}`")

    if context.git.upstream_status:
        upstream = context.git.upstream_status
        sections.append(f"- **Upstream**: {upstream.tracking} (↑{upstream.ahead} ↓{upstream.behind})")

    if context.git.recent_commits:
        sections.append("")
        sections.append("### Recent Commits")
        sections.append("")
        for commit in context.git.recent_commits[:5]:  # Show last 5
            sections.append(f"- `{commit.hash[:7]}` {commit.message} ({commit.author})")

    sections.append("")

    # Task Context
    if context.task:
        sections.append("## Task Context")
        sections.append("")
        task = context.task.task
        sections.append(f"### {task.title}")
        sections.append("")
        sections.append(f"- **ID**: `{task.short_id}`")
        sections.append(f"- **Status**: {task.status}")
        if task.priority:
            sections.append(f"- **Priority**: {task.priority}")
        sections.append(f"- **Type**: {task.task_type} ({task.task_category})")
        if task.notion_url:
            sections.append(f"- **URL**: {task.notion_url}")

        if task.description:
            sections.append("")
            sections.append("#### Description")
            sections.append("")
            sections.append(task.description)

        if task.acceptance_criteria:
            sections.append("")
            sections.append("#### Acceptance Criteria")
            sections.append("")
            sections.append(task.acceptance_criteria)

        if task.ai_summary:
            sections.append("")
            sections.append("#### AI Summary")
            sections.append("")
            sections.append(task.ai_summary)

        # Epic
        if context.task.epic:
            epic = context.task.epic
            sections.append("")
            sections.append(f"### Epic: {epic.name}")
            sections.append("")
            sections.append(f"- **ID**: `{epic.short_id}`")
            sections.append(f"- **Status**: {epic.status}")
            if epic.log_line:
                sections.append(f"- **Log Line**: {epic.log_line}")
            if epic.github_repo:
                sections.append(f"- **GitHub**: {epic.github_repo}")

        # User Stories
        if context.task.user_stories:
            sections.append("")
            sections.append("### User Stories")
            sections.append("")
            for story in context.task.user_stories:
                sections.append(f"#### {story.name} (`{story.short_id}`)")
                sections.append("")
                sections.append(f"**Description**: {story.description}")
                sections.append("")
                sections.append(f"**Acceptance Criteria**: {story.acceptance_criteria}")
                sections.append("")

        # Subtasks
        if context.task.subtasks:
            sections.append("### Subtasks")
            sections.append("")
            for subtask in context.task.subtasks:
                sections.append(f"- [{subtask.status}] {subtask.title} (`{subtask.short_id}`)")
            sections.append("")

    # Sprint Context
    if context.sprint:
        sections.append("## Sprint Context")
        sections.append("")
        sprint = context.sprint.sprint
        sections.append(f"### {sprint.name}")
        sections.append("")
        sections.append(f"- **ID**: `{sprint.short_id}`")
        sections.append(f"- **Status**: {sprint.status}")
        sections.append(f"- **Progress**: {context.sprint.progress:.1%}")

        if sprint.start_date and sprint.end_date:
            sections.append(f"- **Duration**: {sprint.start_date.date()} → {sprint.end_date.date()}")

        if context.sprint.objectives:
            sections.append("")
            sections.append("#### Objectives")
            sections.append("")
            for objective in context.sprint.objectives:
                sections.append(f"- {objective}")

        if context.sprint.tasks:
            sections.append("")
            sections.append(f"#### Sprint Tasks ({len(context.sprint.tasks)})")
            sections.append("")
            for task in context.sprint.tasks[:10]:  # Show first 10
                sections.append(f"- [{task.status}] {task.title} (`{task.short_id}`)")

        sections.append("")

    # Plan Context
    if context.plan:
        sections.append("## Implementation Plan")
        sections.append("")
        plan = context.plan.plan
        sections.append(f"### {plan.title}")
        sections.append("")
        sections.append(f"- **ID**: `{plan.short_id}`")
        sections.append(f"- **Status**: {plan.status} (v{plan.version})")
        sections.append(f"- **Progress**: Step {context.plan.current_step or 0} of {context.plan.status.total_steps}")

        if plan.summary:
            sections.append("")
            sections.append("#### Summary")
            sections.append("")
            sections.append(plan.summary)

        sections.append("")
        sections.append("#### Technical Approach")
        sections.append("")
        sections.append(plan.technical_approach)

        if plan.test_strategy:
            sections.append("")
            sections.append("#### Test Strategy")
            sections.append("")
            sections.append(plan.test_strategy)

        if plan.critical_files:
            sections.append("")
            sections.append("#### Critical Files")
            sections.append("")
            for file in plan.critical_files:
                sections.append(f"- **{file.path}**")
                sections.append(f"  - Changes: {file.changes}")
                sections.append(f"  - Risk: {file.risk}")

        if context.plan.risks_active:
            sections.append("")
            sections.append("#### Active Risks")
            sections.append("")
            for risk in context.plan.risks_active:
                sections.append(f"- **{risk.risk}**")
                sections.append(f"  - Likelihood: {risk.likelihood}, Impact: {risk.impact}")
                sections.append(f"  - Mitigation: {risk.mitigation}")

        if plan.dependencies:
            sections.append("")
            sections.append("#### Dependencies")
            sections.append("")
            for dep in plan.dependencies:
                status = "✓" if dep.installed else "✗"
                version = f" ({dep.version})" if dep.version else ""
                sections.append(f"- {status} **{dep.name}**{version}")
                sections.append(f"  - {dep.purpose}")

        if context.plan.plan_file_path:
            sections.append("")
            sections.append(f"**Plan File**: `{context.plan.plan_file_path}`")

        sections.append("")

    # Knowledge Context
    if context.knowledge.related_docs or context.knowledge.related_plans or context.knowledge.references:
        sections.append("## Knowledge Context")
        sections.append("")

        if context.knowledge.related_docs:
            sections.append("### Related Documents")
            sections.append("")
            for doc in context.knowledge.related_docs:
                sections.append(f"- **{doc.name}** (`{doc.short_id}`) - {doc.document_type} v{doc.version}")

        if context.knowledge.related_plans:
            sections.append("")
            sections.append("### Related Plans")
            sections.append("")
            for plan in context.knowledge.related_plans:
                sections.append(f"- **{plan.title}** (`{plan.short_id}`) - {plan.status}")

        if context.knowledge.references:
            sections.append("")
            sections.append("### References")
            sections.append("")
            for ref in context.knowledge.references:
                sections.append(f"- {ref}")

        sections.append("")

    # Environment Context
    sections.append("## Environment")
    sections.append("")
    sections.append(f"- **Workspace**: `{context.environment.workspace_root}`")
    sections.append(f"- **Python**: {context.environment.python_version}")

    if context.environment.node_version:
        sections.append(f"- **Node**: {context.environment.node_version}")

    if context.environment.uv_lock_hash:
        sections.append(f"- **UV Lock Hash**: `{context.environment.uv_lock_hash[:8]}...`")

    if context.environment.aws_profile:
        sections.append(f"- **AWS Profile**: {context.environment.aws_profile}")

    if context.environment.active_services:
        sections.append(f"- **Active Services**: {', '.join(context.environment.active_services)}")

    sections.append("")

    # Validation Warnings
    warnings = context.validate_state()
    if warnings:
        sections.append("## Warnings")
        sections.append("")
        for warning in warnings:
            sections.append(f"⚠️ {warning}")
        sections.append("")

    # Footer
    sections.append("---")
    sections.append("")
    sections.append("*Generated by `lw context`*")

    return "\n".join(sections)
