#!/usr/bin/env python3
"""Generate MkDocs documentation pages from transpiled examples.

This script reads the artifacts generated by examples/generate_artifacts.py
and creates beautiful markdown documentation pages with syntax highlighting
for each query category (fraud, credit, features).
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any


def load_metadata(artifact_dir: Path) -> dict[str, Any]:
    """Load metadata.json from an artifact directory."""
    metadata_path = artifact_dir / "metadata.json"
    if not metadata_path.exists():
        return {}
    return json.loads(metadata_path.read_text(encoding="utf-8"))


def load_file_safe(file_path: Path) -> str:
    """Safely load a file, returning empty string if not found."""
    if not file_path.exists():
        return ""
    return file_path.read_text(encoding="utf-8")


def escape_html(text: str) -> str:
    """Escape HTML special characters."""
    return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def generate_query_section(
    query_id: str,
    artifact_dir: Path,
    index: int,
) -> str:
    """Generate markdown section for a single query."""
    metadata = load_metadata(artifact_dir)

    cypher_query = load_file_safe(artifact_dir / "query.cypher")
    sql_query = load_file_safe(artifact_dir / "databricks.sql")
    logical_plan = load_file_safe(artifact_dir / "logical_plan.txt")
    error = load_file_safe(artifact_dir / "error.txt")

    description = metadata.get("description", "Query")
    application = metadata.get("application")
    notes = metadata.get("notes")
    success = metadata.get("success", False)

    # Build markdown section - clean format
    lines = [
        f"## {index}. {description}",
        "",
    ]

    # Add application if available
    if application:
        lines.append(f"**Application**: {application}")
        lines.append("")

    # Add notes if available - collapsible
    if notes:
        lines.append("??? note \"Notes\"")
        lines.append("")
        for note_line in notes.strip().split("\n"):
            lines.append(f"    {note_line}")
        lines.append("")

    # OpenCypher query - collapsible but OPEN by default
    lines.append("???+ note \"OpenCypher Query\"")
    lines.append("    ```cypher")
    for cypher_line in cypher_query.strip().split("\n"):
        lines.append(f"    {cypher_line}")
    lines.append("    ```")
    lines.append("")

    # Generated SQL (if successful) - collapsible CLOSED
    if success and sql_query:
        lines.append("??? example \"Generated SQL\"")
        lines.append("    ```sql")
        for sql_line in sql_query.strip().split("\n"):
            lines.append(f"    {sql_line}")
        lines.append("    ```")
        lines.append("")

    # Logical Plan (if successful) - collapsible CLOSED
    if success and logical_plan:
        lines.append("??? info \"Logical Plan\"")
        lines.append("    ```")
        for plan_line in logical_plan.strip().split("\n"):
            lines.append(f"    {plan_line}")
        lines.append("    ```")
        lines.append("")

    # Error (if failed)
    if not success and error:
        lines.append("??? danger \"Error Details\"")
        lines.append("    ```")
        lines.append(f"    {error.strip()}")
        lines.append("    ```")
        lines.append("")

    lines.append("---")
    lines.append("")

    return "\n".join(lines)


def generate_category_page(
    category_name: str,
    artifacts_dir: Path,
    output_path: Path,
) -> None:
    """Generate a documentation page for a query category."""
    category_title = category_name.replace("_", " ").title()

    # Header
    lines = [
        f"# {category_title}",
        "",
        f"This page contains transpiled examples for **{category_title.lower()}** queries.",
        "",
        "Each example shows the original OpenCypher query and its corresponding Databricks SQL translation.",
        "",
        "---",
        "",
    ]

    # Find all query artifacts for this category
    category_artifacts = sorted(artifacts_dir.glob("*"))

    if not category_artifacts:
        lines.append(f"!!! warning \"No examples found for {category_name}\"")
        lines.append("")
    else:
        # Generate section for each query
        for idx, artifact_dir in enumerate(category_artifacts, 1):
            if not artifact_dir.is_dir():
                continue

            query_id = artifact_dir.name
            section = generate_query_section(query_id, artifact_dir, idx)
            lines.append(section)

    # Write to file
    output_path.write_text("\n".join(lines), encoding="utf-8")
    print(f"  ✓ Generated: {output_path.relative_to(output_path.parent.parent)}")


def generate_index_page(
    artifacts_base: Path,
    output_path: Path,
    categories: list[str],
) -> None:
    """Generate the examples index page."""
    lines = [
        "# Query Examples",
        "",
        "Welcome to the gsql2rsql query examples gallery!",
        "",
        "This section demonstrates the transpiler's capabilities across different domains.",
        "Each example shows the original OpenCypher query alongside the generated Databricks SQL.",
        "",
        "## Available Categories",
        "",
    ]

    # Stats for each category
    for category in categories:
        category_dir = artifacts_base / category
        if not category_dir.exists():
            continue

        # Count successes and failures
        total = 0
        success = 0

        for artifact_dir in category_dir.glob("*"):
            if not artifact_dir.is_dir():
                continue
            metadata = load_metadata(artifact_dir)
            total += 1
            if metadata.get("success", False):
                success += 1

        category_title = category.replace("_queries", "").replace("_", " ").title()
        category_link = category.replace("_queries", "")

        lines.append(f"### [{category_title}]({category_link}.md)")
        lines.append("")
        lines.append(f"- **Total Queries**: {total}")
        lines.append(f"- **Successful**: {success}")
        lines.append(f"- **Failed**: {total - success}")
        lines.append("")

    lines.extend(
        [
            "## About These Examples",
            "",
            "All queries are sourced from real-world use cases in:",
            "",
            "- **Fraud Detection**: Graph-based fraud ring detection, anomaly identification",
            "- **Credit Analysis**: Relationship-based credit risk assessment",
            "- **Simple examples**: Simple examples",
            "",
            '!!! tip "Try These Yourself"',
            "    You can run any of these queries through the transpiler using:",
            "    ```bash",
            '    gsql2rsql translate --schema examples/fraud_queries.yaml "<your-query>"',
            "    ```",
            "",
        ]
    )

    output_path.write_text("\n".join(lines), encoding="utf-8")
    print(f"  ✓ Generated: {output_path.relative_to(output_path.parent.parent)}")


def main() -> int:
    """Main entry point."""
    # Paths
    project_root = Path(__file__).parent.parent
    artifacts_base = project_root / "examples" / "out"
    docs_examples = project_root / "docs" / "examples"

    # Create docs/examples directory
    docs_examples.mkdir(parents=True, exist_ok=True)

    print("Generating example documentation pages...")
    print()

    # Check if artifacts exist
    if not artifacts_base.exists():
        print(f"ERROR: Artifacts directory not found: {artifacts_base}")
        print("Please run: python examples/generate_artifacts.py")
        return 1

    # Find categories
    categories = [d.name for d in artifacts_base.iterdir() if d.is_dir()]
    categories = [c for c in categories if not c.startswith(".")]

    if not categories:
        print(f"ERROR: No categories found in {artifacts_base}")
        return 1

    print(f"Found {len(categories)} categories: {', '.join(categories)}")
    print()

    # Generate index page
    index_path = docs_examples / "index.md"
    generate_index_page(artifacts_base, index_path, categories)

    # Generate page for each category
    for category in categories:
        category_dir = artifacts_base / category
        category_file = category.replace("_queries", "")
        output_path = docs_examples / f"{category_file}.md"

        print(f"Processing category: {category}")
        generate_category_page(category, category_dir, output_path)
        print()

    print("✓ Example documentation generated successfully!")
    return 0


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