#!/usr/bin/env python3
"""ReplyMarketing CLI - Main entry point."""

from __future__ import annotations

import asyncio
import sys

import click

from ..core.auth_manager import AuthManager
from ..core.skill_registry import SkillRegistry
from ..providers.provider_manager import ProviderManager
from ..ui import console, run_shell
from ..utils.config import ensure_config_dir
from ..utils.logger import Logger
from .setup_wizard import SetupWizard


@click.command()
@click.option("--setup", is_flag=True, help="Run setup wizard")
@click.option("--version", is_flag=True, help="Show version")
@click.option("--command", "-c", help="Run a single command and exit")
def main(setup: bool, version: bool, command: str | None) -> None:
    """ReplyMarketing CLI - AI-powered marketing assistant for Reply Cash."""

    if version:
        console.print("ReplyMarketing CLI v1.0.0")
        return

    # Ensure config directories exist
    ensure_config_dir()

    Logger.info("Starting ReplyMarketing CLI")

    # Initialize managers
    provider_manager = ProviderManager()
    auth_manager = AuthManager()
    skill_registry = SkillRegistry()

    # Check if setup is needed (provider not configured OR no valid credentials)
    needs_setup = (
        setup 
        or not provider_manager.has_configured_provider() 
        or not auth_manager.has_valid_credentials()
    )

    # Run setup wizard if needed
    if needs_setup:
        wizard = SetupWizard(provider_manager, auth_manager, skill_registry)
        if not wizard.run():
            console.print("[red]Setup incomplete. Exiting.[/red]")
            sys.exit(1)

    # Reload from disk after setup
    try:
        provider_manager.reload_from_disk()
        auth_manager.reload_from_disk()
        skill_registry.initialize()
    except Exception as e:
        console.print(f"[red]Error initializing: {e}[/red]")
        sys.exit(1)

    # Run shell
    success = run_shell(provider_manager, auth_manager, skill_registry)
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()
