"""Root Typer app + callback + global options for send-message."""

import os

import typer

from cli_framework import ForceColorOption, NoColorOption, create_app, get_console, setup_logging
from send_message import __version__
from send_message.context import SendMessageContext

app = create_app(
    name="send-message",
    help="Extract and deliver AI agent session messages.",
)

# Register commands by importing their modules (each decorates @app.command)
from send_message.commands import list_messages as _list_messages  # noqa: E402,F401
from send_message.commands import list_sessions as _list_sessions  # noqa: E402,F401
from send_message.commands import preview as _preview  # noqa: E402,F401
from send_message.commands import send as _send  # noqa: E402,F401


@app.callback()
def main(
    ctx: typer.Context,
    tool: str = typer.Option(None, "--tool", "-t", help="AI agent tool (devin, opencode, copilot)"),
    session_id: str = typer.Option(
        None, "--session-id", "-S", help="Session ID (skip auto-detection)"
    ),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose logging"),
    no_color: NoColorOption = False,
    color: ForceColorOption = False,
    version: bool = typer.Option(False, "--version", "-V", help="Show version and exit"),
) -> None:
    """Extract and deliver AI agent session messages."""
    console = get_console()
    if version:
        console.print(f"send-message {__version__}")
        raise typer.Exit()
    setup_logging(verbose)

    # Env var fallback: CLI options take priority, then env vars, then None
    resolved_tool = tool or os.environ.get("SEND_MESSAGE_TOOL")
    resolved_session = session_id or os.environ.get("SEND_MESSAGE_SESSION")

    ctx.obj = SendMessageContext(
        console=console,
        verbose=verbose,
        tool=resolved_tool,
        session_id=resolved_session,
    )


def run() -> None:
    """Run the CLI (for script entry point)."""
    app()


if __name__ == "__main__":
    run()
