"""Documentation formatters for TripWire CLI.

Generates documentation in various formats (Markdown, HTML, JSON) from
environment variable specifications.
"""

import json

from tripwire.scanner import EnvVarInfo


def generate_markdown_docs(variables: dict[str, EnvVarInfo]) -> str:
    """Generate markdown documentation.

    Args:
        variables: Dictionary of variable information

    Returns:
        Markdown formatted documentation
    """
    from tripwire.scanner import format_default_value

    lines = [
        "# Environment Variables",
        "",
        "This document describes all environment variables used in this project.",
        "",
        "## Required Variables",
        "",
        "| Variable | Type | Description | Validation |",
        "|----------|------|-------------|------------|",
    ]

    required_vars = sorted([v for v in variables.values() if v.required], key=lambda v: v.name)

    if not required_vars:
        lines.append("| - | - | - | - |")
    else:
        for var in required_vars:
            validation = []
            if var.format:
                validation.append(f"Format: {var.format}")
            if var.choices:
                validation.append(f"Choices: {', '.join(str(c) for c in var.choices)}")
            if var.pattern:
                validation.append(f"Pattern: `{var.pattern}`")

            validation_str = "; ".join(validation) if validation else "-"
            desc = var.description or "-"

            lines.append(f"| `{var.name}` | {var.var_type} | {desc} | {validation_str} |")

    lines.extend(
        [
            "",
            "## Optional Variables",
            "",
            "| Variable | Type | Default | Description | Validation |",
            "|----------|------|---------|-------------|------------|",
        ]
    )

    optional_vars = sorted([v for v in variables.values() if not v.required], key=lambda v: v.name)

    if not optional_vars:
        lines.append("| - | - | - | - | - |")
    else:
        for var in optional_vars:
            validation = []
            if var.format:
                validation.append(f"Format: {var.format}")
            if var.choices:
                validation.append(f"Choices: {', '.join(str(c) for c in var.choices)}")
            if var.pattern:
                validation.append(f"Pattern: `{var.pattern}`")

            validation_str = "; ".join(validation) if validation else "-"
            desc = var.description or "-"
            default_str = format_default_value(var.default) or "-"

            lines.append(f"| `{var.name}` | {var.var_type} | `{default_str}` | {desc} | {validation_str} |")

    lines.extend(
        [
            "",
            "## Usage",
            "",
            "To use these variables in your Python code:",
            "",
            "```python",
            "from tripwire import env",
            "",
            "# Required variable",
            "api_key = env.require('API_KEY', description='API key for service')",
            "",
            "# Optional variable with default",
            "debug = env.optional('DEBUG', default=False, type=bool)",
            "```",
            "",
            "---",
            "",
            "*Generated by [TripWire](https://github.com/Daily-Nerd/TripWire)*",
        ]
    )

    return "\n".join(lines)


def generate_html_docs(variables: dict[str, EnvVarInfo]) -> str:
    """Generate HTML documentation.

    Args:
        variables: Dictionary of variable information

    Returns:
        HTML formatted documentation
    """
    from tripwire.scanner import format_default_value

    required_vars = sorted([v for v in variables.values() if v.required], key=lambda v: v.name)
    optional_vars = sorted([v for v in variables.values() if not v.required], key=lambda v: v.name)

    html = """<!DOCTYPE html>
<html>
<head>
    <title>Environment Variables Documentation</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1 { color: #333; }
        h2 { color: #555; border-bottom: 2px solid #ddd; padding-bottom: 10px; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { padding: 12px; text-align: left; border: 1px solid #ddd; }
        th { background-color: #f5f5f5; font-weight: bold; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        code { background-color: #f5f5f5; padding: 2px 6px; border-radius: 3px; }
        .required { color: #c00; }
        .optional { color: #060; }
    </style>
</head>
<body>
    <h1>Environment Variables</h1>
    <p>This document describes all environment variables used in this project.</p>
"""

    html += "    <h2>Required Variables</h2>\n"
    html += "    <table>\n"
    html += "        <tr><th>Variable</th><th>Type</th><th>Description</th><th>Validation</th></tr>\n"

    for var in required_vars:
        validation = []
        if var.format:
            validation.append(f"Format: {var.format}")
        if var.choices:
            validation.append(f"Choices: {', '.join(str(c) for c in var.choices)}")
        validation_str = "; ".join(validation) if validation else "-"
        desc = var.description or "-"

        html += f"        <tr><td><code>{var.name}</code></td><td>{var.var_type}</td><td>{desc}</td><td>{validation_str}</td></tr>\n"

    html += "    </table>\n"

    html += "    <h2>Optional Variables</h2>\n"
    html += "    <table>\n"
    html += "        <tr><th>Variable</th><th>Type</th><th>Default</th><th>Description</th><th>Validation</th></tr>\n"

    for var in optional_vars:
        validation = []
        if var.format:
            validation.append(f"Format: {var.format}")
        if var.choices:
            validation.append(f"Choices: {', '.join(str(c) for c in var.choices)}")
        validation_str = "; ".join(validation) if validation else "-"
        desc = var.description or "-"
        default_str = format_default_value(var.default) or "-"

        html += f"        <tr><td><code>{var.name}</code></td><td>{var.var_type}</td><td><code>{default_str}</code></td><td>{desc}</td><td>{validation_str}</td></tr>\n"

    html += "    </table>\n"
    html += """
    <hr>
    <p><em>Generated by <a href="https://github.com/Daily-Nerd/TripWire">TripWire</a></em></p>
</body>
</html>
"""

    return html


def generate_json_docs(variables: dict[str, EnvVarInfo]) -> str:
    """Generate JSON documentation.

    Args:
        variables: Dictionary of variable information

    Returns:
        JSON formatted documentation
    """
    from typing import Any

    doc: dict[str, Any] = {"variables": []}

    for var in sorted(variables.values(), key=lambda v: v.name):
        var_doc = {
            "name": var.name,
            "type": var.var_type,
            "required": var.required,
            "default": var.default,
            "description": var.description,
            "secret": var.secret,
        }

        if var.format:
            var_doc["format"] = var.format
        if var.pattern:
            var_doc["pattern"] = var.pattern
        if var.choices:
            var_doc["choices"] = var.choices
        if var.min_val is not None:
            var_doc["min_value"] = var.min_val
        if var.max_val is not None:
            var_doc["max_value"] = var.max_val

        doc["variables"].append(var_doc)

    return json.dumps(doc, indent=2)


__all__ = ["generate_markdown_docs", "generate_html_docs", "generate_json_docs"]
