"""CLI command handler for dry-run validation."""

from __future__ import annotations

import contextlib
import logging
import sys
from pathlib import Path
from types import SimpleNamespace

import click

from slack_chat_migrator.cli.common import (
    cli,
    common_options,
    handle_exception,
    show_security_warning,
)
from slack_chat_migrator.cli.migrate_cmd import (
    MigrationOrchestrator,
    _print_config_panel,
    _quiet_console,
    create_migration_output_directory,
)
from slack_chat_migrator.cli.renderers import error_panel, get_console
from slack_chat_migrator.utils.logging import log_with_context, setup_logger

# ---------------------------------------------------------------------------
# validate subcommand
# ---------------------------------------------------------------------------


@cli.command()
@common_options
@click.option(
    "--export_path",
    required=True,
    help="Path to Slack export directory",
)
@click.option(
    "--dry_run",
    is_flag=True,
    default=False,
    hidden=True,
    help="(ignored — validate always runs in dry-run mode)",
)
def validate(
    creds_path: str | None,
    export_path: str,
    workspace_admin: str | None,
    config: str,
    verbose: bool,
    debug_api: bool,
    dry_run: bool,
) -> None:
    """Dry-run validation of export data, user mappings, and channels.

    Equivalent to ``migrate --dry_run`` but expressed as an explicit command.

    Args:
        creds_path: Path to service account credentials JSON.
        export_path: Path to Slack export directory.
        workspace_admin: Email of workspace admin to impersonate.
        config: Path to config YAML.
        verbose: Enable verbose console logging.
        debug_api: Enable detailed API request/response logging.
        dry_run: Ignored — validate always runs in dry-run mode.
    """
    if dry_run:
        log_with_context(
            logging.INFO,
            "Note: --dry_run is redundant with 'validate' (always dry-run).",
        )

    # Check if config file exists; suggest init if missing
    config_path = Path(config)
    if not config_path.exists():
        console = get_console()
        console.print(
            error_panel(
                "Config file not found",
                f"[bold]{config}[/bold] does not exist.\n\n"
                "Generate one with:\n"
                "  [bold]slack-chat-migrator init --export_path "
                f"{export_path}[/bold]",
            )
        )
        if click.confirm("Run init now?", default=True):
            from slack_chat_migrator.cli.init_cmd import init

            ctx = click.Context(init)
            ctx.invoke(init, export_path=export_path, output=config)
            # Re-check after init
            if not config_path.exists():
                click.echo("Config file still not found. Aborting.")
                sys.exit(1)
        else:
            sys.exit(1)

    args = SimpleNamespace(
        creds_path=creds_path,
        export_path=export_path,
        workspace_admin=workspace_admin,
        config=config,
        verbose=verbose,
        debug_api=debug_api,
        dry_run=True,  # always dry run
        update_mode=False,
        skip_permission_check=False,
    )

    output_dir = create_migration_output_directory()
    with _quiet_console() if sys.stdout.isatty() else contextlib.nullcontext():
        setup_logger(args.verbose, args.debug_api, output_dir)

    # Show config panel (Rich on TTY, log lines otherwise)
    _print_config_panel(args, output_dir)
    with _quiet_console() if sys.stdout.isatty() else contextlib.nullcontext():
        log_with_context(logging.INFO, f"Output directory: {output_dir}")

    # Standalone permission check is handled by orchestrator.validate_prerequisites()
    # which prints its own preflight status lines.
    orchestrator = MigrationOrchestrator(args)
    orchestrator.output_dir = output_dir

    try:
        orchestrator.validate_prerequisites()
        orchestrator.run_migration()
    except Exception as e:
        handle_exception(e)
        sys.exit(1)
    finally:
        orchestrator.cleanup()
        show_security_warning()
