#!/usr/bin/env python3
"""Generate architecture documentation from tach analysis.

Creates:
- docs/architecture/dependencies/dependency_graph.html - Interactive visual diagram
"""

import subprocess
import sys
from pathlib import Path


def run_command(cmd: list[str]) -> str:
    """Run a command and return stdout."""
    result = subprocess.run(
        cmd, capture_output=True, text=True, cwd=Path(__file__).parent.parent
    )
    return result.stdout


def get_mermaid_diagram() -> str:
    """Get mermaid diagram from tach."""
    output = run_command(["tach", "show", "--mermaid", "-o", "-"])
    # Remove the NOTE line at the end
    lines = output.strip().split("\n")
    diagram_lines = []
    for line in lines:
        if line.startswith("NOTE:") or line.startswith("To visualize"):
            break
        diagram_lines.append(line)
    return "\n".join(diagram_lines)


def generate_graph_html(mermaid_content: str) -> str:
    """Generate the dependency graph HTML."""
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCP Tools Py - Dependency Graph</title>
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background: #1a1a2e;
            color: #eee;
        }}
        h1 {{
            text-align: center;
            color: #00d9ff;
            margin-bottom: 10px;
        }}
        .subtitle {{
            text-align: center;
            color: #888;
            margin-bottom: 30px;
        }}
        .legend {{
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }}
        .legend-item {{
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: #252540;
            border-radius: 8px;
        }}
        .legend-color {{
            width: 16px;
            height: 16px;
            border-radius: 4px;
        }}
        .mermaid {{
            display: flex;
            justify-content: center;
            background: #16213e;
            border-radius: 12px;
            padding: 30px;
            overflow: auto;
        }}
        .info {{
            max-width: 800px;
            margin: 30px auto;
            padding: 20px;
            background: #252540;
            border-radius: 12px;
        }}
        .info h2 {{
            color: #00d9ff;
            margin-top: 0;
        }}
        .info ul {{
            line-height: 1.8;
        }}
        code {{
            background: #1a1a2e;
            padding: 2px 6px;
            border-radius: 4px;
            color: #00d9ff;
        }}
    </style>
</head>
<body>
    <h1>MCP Tools Py - Module Dependency Graph</h1>
    <p class="subtitle">Generated by tach - Architectural Boundary Enforcement</p>

    <div class="legend">
        <div class="legend-item">
            <div class="legend-color" style="background: #ff6b6b;"></div>
            <span>Entry Point</span>
        </div>
        <div class="legend-item">
            <div class="legend-color" style="background: #4ecdc4;"></div>
            <span>Server</span>
        </div>
        <div class="legend-item">
            <div class="legend-color" style="background: #45b7d1;"></div>
            <span>Checker Implementation</span>
        </div>
        <div class="legend-item">
            <div class="legend-color" style="background: #96ceb4;"></div>
            <span>Utilities</span>
        </div>
    </div>

    <div class="mermaid">
{mermaid_content}
    </div>

    <div class="info">
        <h2>Architecture Layers</h2>
        <ul>
            <li><strong>Entry Point</strong> - CLI argument parsing and server startup (<code>main</code>)</li>
            <li><strong>Server</strong> - MCP tool registration and result formatting (<code>server</code>)</li>
            <li><strong>Checker Implementation</strong> - Tool-specific integrations (<code>code_checker_pytest</code>, <code>code_checker_pylint</code>, <code>code_checker_mypy</code>)</li>
            <li><strong>Utilities</strong> - Shared infrastructure (<code>utils</code>, <code>log_utils</code>)</li>
        </ul>

        <h2>Commands</h2>
        <ul>
            <li><code>tach check</code> - Verify architectural boundaries</li>
            <li><code>tools/tach_docs.bat</code> or <code>tools/tach_docs.sh</code> - Regenerate this documentation</li>
            <li><code>tools/pydeps_graph.bat</code> or <code>tools/pydeps_graph.sh</code> - Generate pydeps visualization</li>
        </ul>
    </div>

    <script>
        mermaid.initialize({{
            startOnLoad: true,
            theme: 'dark',
            flowchart: {{
                useMaxWidth: true,
                htmlLabels: true,
                curve: 'basis'
            }}
        }});
    </script>
</body>
</html>
"""


def main() -> int:
    """Generate architecture documentation."""
    print("Generating architecture documentation...")

    # Ensure output directory exists
    output_dir = Path(__file__).parent.parent / "docs" / "architecture" / "dependencies"
    output_dir.mkdir(parents=True, exist_ok=True)

    # Generate dependency graph
    print("  - Generating dependency graph...")
    mermaid = get_mermaid_diagram()
    if not mermaid.strip():
        print("    WARNING: tach show --mermaid returned empty output")
        print("    Make sure tach is installed and tach.toml is configured")
        return 1

    graph_html = generate_graph_html(mermaid)
    graph_path = output_dir / "dependency_graph.html"
    graph_path.write_text(graph_html, encoding="utf-8")
    print(f"    Created: {graph_path}")

    print("\nDone! Open docs/architecture/dependencies/dependency_graph.html to view.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
