"""Command-line interface for words-to-readlang.

This module provides the Typer-based CLI for converting vocabulary files
to Readlang CSV format.
"""

from pathlib import Path
from typing import Optional

import typer
from rich.console import Console
from typing_extensions import Annotated

from .__version__ import __version__
from .core import Converter
from .parsers import list_parsers

_err = Console(stderr=True)

app = typer.Typer(
    name="words-to-readlang",
    help="Convert vocabulary exports to Readlang CSV format.",
    add_completion=False,
)


def version_callback(value: bool) -> None:
    """Print version and exit if --version flag is set."""
    if value:
        typer.echo(f"words-to-readlang version {__version__}")
        raise typer.Exit()


@app.command()
def convert(
    input_file: Annotated[
        Path,
        typer.Argument(
            help="Path to input vocabulary file",
            exists=True,
            file_okay=True,
            dir_okay=False,
            readable=True,
        ),
    ],
    output_file: Annotated[
        Path, typer.Argument(help="Path for output Readlang CSV file")
    ],
    format: Annotated[
        str,
        typer.Option(
            "--format",
            "-f",
            help="Input file format (pod101, languagereactor or lr)",
        ),
    ],
    fetch: Annotated[
        bool,
        typer.Option(
            "--fetch",
            help="Fetch missing example sentences from Tatoeba (with Leipzig as fallback)",
        ),
    ] = False,
    lang: Annotated[
        str,
        typer.Option(
            "--lang",
            help="Source language code for Tatoeba/Leipzig (e.g., fin, swe)",
        ),
    ] = "fin",
    version: Annotated[
        Optional[bool],
        typer.Option(
            "--version",
            callback=version_callback,
            is_eager=True,
            help="Show version and exit",
        ),
    ] = None,
) -> None:
    """Convert vocabulary file to Readlang CSV format.

    \b
    Examples:
      words-to-readlang input.csv output.csv --format pod101

      words-to-readlang saved.csv output.csv --format languagereactor --fetch

      words-to-readlang words.csv out.csv -f pod101 --fetch --lang swe
    """
    # Validate format
    available = list_parsers()
    if format not in available:
        _err.print(
            f"[red]Error:[/red] Unknown format [bold]{format!r}[/bold]. "
            f"Available: {', '.join(sorted(available.keys()))}"
        )
        raise typer.Exit(1)

    # Create converter
    converter = Converter(fetch_examples=fetch, src_lang=lang, verbose=True)

    try:
        converter.convert(input_file, output_file, format)
    except Exception as e:
        _err.print(f"[red]Error:[/red] {e}")
        raise typer.Exit(1)


@app.command()
def serve(
    host: Annotated[
        str,
        typer.Option("--host", "-h", help="Address to bind to"),
    ] = "127.0.0.1",
    port: Annotated[
        int,
        typer.Option("--port", "-p", help="Port to listen on"),
    ] = 5000,
    debug: Annotated[
        bool,
        typer.Option("--debug", help="Enable Flask debug mode with auto-reload"),
    ] = False,
) -> None:
    """Start the web interface.

    \b
    Example:
      words-to-readlang serve
      words-to-readlang serve --port 8080
      words-to-readlang serve --host 0.0.0.0 --port 8080 --debug
    """
    from .web.app import create_app

    flask_app = create_app()
    typer.echo(f"Starting server at http://{host}:{port}")
    flask_app.run(host=host, port=port, debug=debug)


@app.command()
def list_formats() -> None:
    """List all available input formats.

    \b
    Example:
      words-to-readlang list-formats
    """
    parsers = list_parsers()
    typer.echo("Available input formats:\n")
    for name in sorted(parsers.keys()):
        description = parsers[name]
        typer.echo(f"  {name:20} {description}")


def main() -> None:
    """Entry point for the CLI."""
    app()


if __name__ == "__main__":
    main()
