"""CLI entry point using typer."""

from __future__ import annotations

import asyncio
from pathlib import Path

import typer

app = typer.Typer(
    name="ai4gh",
    help="Comprehensive Python SDK for GA4GH specifications.",
    no_args_is_help=True,
)

mcp_app = typer.Typer(help="MCP server commands.")
app.add_typer(mcp_app, name="mcp")

config_app = typer.Typer(help="Configuration management.")
app.add_typer(config_app, name="config")


@app.command()
def version() -> None:
    """Show version information."""
    from ai4gh import __version__

    typer.echo(f"ai4gh {__version__}")


@mcp_app.command()
def serve() -> None:
    """Start the GA4GH MCP server on stdio transport."""
    from ai4gh.mcp.server import run_server

    asyncio.run(run_server())


@config_app.command("show")
def config_show() -> None:
    """Show current configuration."""
    from ai4gh.core.config import Config

    cfg = Config()
    typer.echo(f"Base URL: {cfg.base_url}")
    typer.echo(f"Timeout: {cfg.timeout}s")
    typer.echo(f"Max Retries: {cfg.max_retries}")
    typer.echo(f"Log Level: {cfg.log_level}")


@config_app.command("init")
def config_init() -> None:
    """Initialize a configuration file."""
    config_path = Path("ai4gh.toml")
    if config_path.exists():
        typer.echo(f"Config already exists: {config_path}")
        raise typer.Exit(1)
    config_path.write_text(
        '[ai4gh]\nbase_url = ""\ntimeout = 30\nmax_retries = 3\nlog_level = "INFO"\n'
    )
    typer.echo(f"Created {config_path}")


@app.command("test")
def test_compliance(
    spec: str = typer.Argument(help="GA4GH specification to test (beacon, drs, wes, etc.)"),
    url: str = typer.Argument(help="Server base URL to test"),
    format: str = typer.Option(
        "text", "--format", "-f", help="Output format: text, json, html, junit"
    ),
    output: str | None = typer.Option(None, "--output", "-o", help="Output file path"),
) -> None:
    """Run GA4GH compliance tests against a server."""
    # Import suites to trigger registration
    import ai4gh.compliance.suites  # noqa: F401
    from ai4gh.compliance.runner import get_suite

    suite_cls = get_suite(spec)
    if suite_cls is None:
        from ai4gh.compliance.runner import list_suites

        available = ", ".join(list_suites())
        typer.echo(f"Unknown spec: {spec}. Available: {available}", err=True)
        raise typer.Exit(1)

    suite = suite_cls(base_url=url)
    result = asyncio.run(suite.run())

    if format == "json":
        from ai4gh.compliance.report import to_json

        content = to_json(result)
    elif format == "html":
        from ai4gh.compliance.report import to_html

        content = to_html(result)
    elif format == "junit":
        from ai4gh.compliance.report import to_junit_xml

        content = to_junit_xml(result)
    else:
        # Text format
        lines = [
            f"GA4GH Compliance: {result.spec}",
            f"Server: {result.base_url}",
            f"Tests: {result.total} | Passed: {result.passed} | "
            f"Failed: {result.failed} | Skipped: {result.skipped} | "
            f"Errors: {result.errors}",
            f"Success Rate: {result.success_rate:.1f}%",
            f"Duration: {result.duration_ms:.1f}ms",
            "",
        ]
        for r in result.results:
            status_icon = {
                "pass": "PASS",
                "fail": "FAIL",
                "skip": "SKIP",
                "error": "ERR ",
            }.get(r.status.value, "????")
            line = f"  [{status_icon}] {r.name}"
            if r.message:
                line += f" - {r.message}"
            lines.append(line)
        content = "\n".join(lines)

    if output:
        Path(output).write_text(content)
        typer.echo(f"Report written to {output}")
    else:
        typer.echo(content)


@app.command("list-specs")
def list_specs() -> None:
    """List available compliance test suites."""
    import ai4gh.compliance.suites  # noqa: F401
    from ai4gh.compliance.runner import list_suites

    specs = list_suites()
    if not specs:
        typer.echo("No compliance suites available.")
        return
    typer.echo("Available compliance suites:")
    for spec in specs:
        typer.echo(f"  - {spec}")


if __name__ == "__main__":
    app()
