"""WORAi root CLI."""

from __future__ import annotations

import logging

import typer

from worai.config import load_config
from worai.errors import WoraError
from worai.logging import setup_logging

app = typer.Typer(add_completion=True, no_args_is_help=True)


@app.callback()
def main(
    ctx: typer.Context,
    config: str | None = typer.Option(None, "--config", help="Path to config TOML."),
    profile: str | None = typer.Option(None, "--profile", help="Config profile name."),
    log_level: str = typer.Option("info", "--log-level", help="Log level."),
    log_format: str = typer.Option("text", "--log-format", help="Log format: text or json."),
    quiet: bool = typer.Option(False, "--quiet", help="Only warnings and errors."),
) -> None:
    """WORAi command-line tools."""
    setup_logging(level=log_level, fmt=log_format, quiet=quiet)
    ctx.obj = {
        "config": load_config(config, profile),
        "log_level": log_level,
        "log_format": log_format,
        "quiet": quiet,
    }


@app.command("version")
def version() -> None:
    """Print version."""
    from worai import __version__

    typer.echo(__version__)


def _install_commands() -> None:
    from worai.commands import (
        canonicalize_duplicate_pages,
        delete_entities_from_csv,
        dedupe,
        find_faq_page_wrong_type,
        find_missing_names,
        find_url_by_type,
        google_search_console,
        link_groups,
        patch,
        seocheck,
        upload_entities_from_turtle,
    )

    app.add_typer(seocheck.app, name="seocheck")
    app.add_typer(google_search_console.app, name="google-search-console")
    app.add_typer(dedupe.app, name="dedupe")
    app.add_typer(canonicalize_duplicate_pages.app, name="canonicalize-duplicate-pages")
    app.add_typer(delete_entities_from_csv.app, name="delete-entities-from-csv")
    app.add_typer(find_faq_page_wrong_type.app, name="find-faq-page-wrong-type")
    app.add_typer(find_missing_names.app, name="find-missing-names")
    app.add_typer(find_url_by_type.app, name="find-url-by-type")
    app.add_typer(link_groups.app, name="link-groups")
    app.add_typer(patch.app, name="patch")
    app.add_typer(upload_entities_from_turtle.app, name="upload-entities-from-turtle")


_install_commands()


def run() -> None:
    try:
        app()
    except WoraError as exc:
        logging.getLogger("worai").error(str(exc))
        raise SystemExit(exc.exit_code) from exc
