# standard
import importlib
from pathlib import Path

# third party
import typer

# custom
from sunwaee.core.logger import get_logger
from sunwaee.core.output import console, success

_log = get_logger("cli")

app = typer.Typer(
    name="sunwaee",
    help="SUNWÆE CLI - The Almost Everything CLI.",
    no_args_is_help=True,
)


def _discover_modules() -> None:
    """Auto-discover and register all modules in sunwaee/modules/."""
    import sunwaee.modules as modules_pkg

    modules_path = Path(modules_pkg.__file__).parent
    for item in sorted(modules_path.iterdir()):
        if item.is_dir() and not item.name.startswith("_"):
            try:
                mod = importlib.import_module(f"sunwaee.modules.{item.name}")
                if hasattr(mod, "app"):
                    app.add_typer(mod.app)
            except ImportError:  # pragma: no cover
                pass


@app.command("init")
def init(
    workspace: str = typer.Option(
        "personal", "--workspace", "-w", help="Name of the default workspace to create"
    ),
    force: bool = typer.Option(
        False, "--force", help="Re-initialise even if already set up"
    ),
) -> None:
    """Initialise SUNWÆE: create config and default workspace."""
    from sunwaee.config import (
        _config_file,
        _load_config,
        get_workspaces_base_dir,
        set_default_workspace,
    )

    cfg_file = _config_file()
    workspace_dir = get_workspaces_base_dir() / workspace

    already_exists = cfg_file.exists() and workspace_dir.exists()
    if already_exists and not force:

        def _already() -> None:  # pragma: no cover
            console.print("[dim]Already initialised.[/dim]")
            console.print(f"  Config:    [dim]{cfg_file}[/dim]")
            console.print(f"  Workspace: [dim]{workspace_dir}[/dim]")
            console.print("[dim]Use --force to reinitialise.[/dim]")

        success(
            {
                "config": str(cfg_file),
                "workspace": workspace,
                "path": str(workspace_dir),
            },
            human_fn=_already,
        )
        return

    _load_config()
    workspace_dir.mkdir(parents=True, exist_ok=True)
    set_default_workspace(workspace)
    _log.info("Initialised: config=%s workspace=%s", cfg_file, workspace_dir)

    def _done() -> None:  # pragma: no cover
        console.print("[green]Initialised SUNWÆE[/green]")
        console.print(f"  Config:    [dim]{cfg_file}[/dim]")
        console.print(f"  Workspace: [dim]{workspace_dir}[/dim]")

    success(
        {"config": str(cfg_file), "workspace": workspace, "path": str(workspace_dir)},
        human_fn=_done,
    )


_discover_modules()
