"""Typer CLI entrypoint for harvest-session-dbs.

Wires colour flags, typed context, and command registration.
"""

from __future__ import annotations

import sys
from pathlib import Path
from typing import Annotated

import typer
from loguru import logger
from rich.console import Console

from harvest_session_dbs.config.settings import (
    DEFAULT_FILENAME,
    ENV_CONFIG,
    resolve_config_path,
)

app = typer.Typer(
    name="harvest-session-dbs",
    help="Harvest AI agent session databases from defined hosts for test fixtures.",
    add_completion=True,
    no_args_is_help=True,
    rich_markup_mode="rich",
)

config_app = typer.Typer(help="Manage the harvest-session-dbs configuration file.")
app.add_typer(config_app, name="config", no_args_is_help=True)

_console = Console()


def get_console() -> Console:
    """Get the shared console instance."""
    return _console


class AppContext:
    """Typed context object for Typer commands.

    Attributes:
        console: Shared Rich console instance.
        config_path: Resolved path to the config file.
    """

    def __init__(self, console: Console, config_path: Path) -> None:
        self.console = console
        self.config_path = config_path


def get_context(ctx: typer.Context) -> AppContext:
    """Extract the typed AppContext from a Typer context.

    Args:
        ctx: Typer context object.

    Returns:
        The AppContext instance stored in ctx.obj.
    """
    return ctx.obj  # type: ignore[no-any-return]


# Import commands to register them with the app.
# This import must come after `app` and `config_app` are defined above.
from harvest_session_dbs.cli import commands  # noqa: E402, F401


@app.callback(invoke_without_command=True)
def main_callback(
    ctx: typer.Context,
    config: Annotated[
        Path | None,
        typer.Option(
            "--config",
            "-c",
            help="Path to harvest-session-dbs.yaml config file.",
            envvar=ENV_CONFIG,
            show_default=True,
        ),
    ] = None,
    verbose: Annotated[
        bool,
        typer.Option("--verbose", "-v", help="Enable verbose logging."),
    ] = False,
) -> None:
    """Harvest AI agent session databases from defined hosts for test fixtures."""
    # Configure logging
    logger.remove()
    level = "DEBUG" if verbose else "INFO"
    logger.add(sys.stderr, level=level)

    config_path = resolve_config_path(
        config,
        env_var=ENV_CONFIG,
        default_filename=DEFAULT_FILENAME,
    )
    ctx.obj = AppContext(console=get_console(), config_path=config_path)
