"""
Architecture File Writer.

Writes the updated Mermaid diagram to the output file with metadata.
"""

import os
from datetime import datetime
from pathlib import Path

from rich.console import Console

from umbra.agents.state import GraphState

console = Console()

TEMPLATE = """# 🏗️ Live Architecture

> **Auto-generated by Umbra** - Do not edit manually
> Last updated: {timestamp}

{summary_section}

## System Overview

```mermaid
{mermaid}
```

## Recent Changes

{history}
"""


def writer_node(state: GraphState) -> GraphState:
    print("lol")
    """
    Write the updated architecture to file.

    Input: updated_mermaid, file_path (the changed file), analysis_result
    Output: (writes to disk, returns unchanged state)
    """
    updated = state.get("updated_mermaid")
    if not updated:
        return state

    if not state.get("is_valid_mermaid", False):
        console.print("[yellow]   SKIP: invalid mermaid[/yellow]")
        return state

    output_path = Path(os.getenv("OUTPUT_FILE", "./output/LIVE_ARCHITECTURE.md"))
    output_path.parent.mkdir(parents=True, exist_ok=True)

    # Load existing history and summary
    history = load_existing_history(output_path)
    summary_section = load_existing_summary(output_path)

    # Add new entry
    analysis = state.get("analysis_result")
    change_type = analysis.change_type if analysis else "unknown"
    file_name = Path(state.get("file_path", "unknown")).name

    new_entry = (
        f"| {datetime.now().strftime('%H:%M')} | `{file_name}` | {change_type} |"
    )

    # Prepend new entry and keep only last 10
    history_lines = history.strip().split("\n")
    # Find where the table data starts (after header)
    header_end = 2  # Skip "| Time | File | Change |" and separator
    if len(history_lines) > header_end:
        data_lines = history_lines[header_end:]
        data_lines = [new_entry] + data_lines[:9]  # Keep last 9 + new = 10
        history = "\n".join(history_lines[:header_end] + data_lines)
    else:
        history = history + "\n" + new_entry

    # Generate content
    content = TEMPLATE.format(
        timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        summary_section=summary_section,
        mermaid=updated,
        history=history,
    )

    # Write directly to file (Windows doesn't like rename when file is open)
    try:
        output_path.write_text(content, encoding="utf-8")
        console.print(f"[green]   OK: Written to {output_path}[/green]")
    except Exception as e:
        console.print(f"[red]   ERROR: Write failed: {e}[/red]")

    return state


def load_existing_history(path: Path) -> str:
    """Extract history section from existing file or return default."""
    default_history = "| Time | File | Change |\n|------|------|--------|"

    if not path.exists():
        return default_history

    try:
        content = path.read_text(encoding="utf-8")

        # Find history section
        if "## Recent Changes" in content:
            history_start = content.index("## Recent Changes") + len("## Recent Changes")
            history = content[history_start:].strip()
            if history:
                return history
    except Exception:
        pass

    return default_history


def load_existing_summary(path: Path) -> str:
    """Extract project summary section from existing file or return empty."""
    if not path.exists():
        return ""

    try:
        content = path.read_text(encoding="utf-8")

        # Find summary section
        if "## Project Summary" in content:
            summary_start = content.index("## Project Summary")
            
            # Find the end (next ## section)
            rest = content[summary_start:]
            lines = rest.split("\n")
            summary_lines = [lines[0]]  # "## Project Summary"
            
            for line in lines[1:]:
                if line.startswith("## "):
                    break
                summary_lines.append(line)
            
            summary = "\n".join(summary_lines).strip()
            if summary:
                return summary
    except Exception:
        pass

    return ""


def load_current_mermaid(output_path: str | Path) -> str:
    """Load current Mermaid diagram from output file."""
    from umbra.agents.state import INITIAL_DIAGRAM

    path = Path(output_path)
    if not path.exists():
        return INITIAL_DIAGRAM

    try:
        content = path.read_text(encoding="utf-8")

        # Extract mermaid block
        if "```mermaid" in content:
            start = content.index("```mermaid") + len("```mermaid")
            end = content.index("```", start)
            return content[start:end].strip()
    except Exception:
        pass

    return INITIAL_DIAGRAM

