import click
from pathlib import Path
import os
import subprocess
from importlib.resources import files
from . import docker
from .sync.manager import SyncManager


def _ensure_app_directory() -> Path:
    """Ensure the app directory exists with necessary files and subdirectories."""
    app_dir = Path(click.get_app_dir("ccat", force_posix=True))

    # Create app directory if it doesn't exist
    app_dir.mkdir(parents=True, exist_ok=True)

    # Copy compose.yml if it doesn't exist
    compose_target = app_dir / "compose.yml"
    if not compose_target.exists():
        compose_source = files("cheshire_cat_cli") / "compose.yml"
        with compose_source.open("rb") as src:
            compose_target.write_bytes(src.read())

    return app_dir


@click.group()
def cli():
    """Chetshire-Cat AI cli manager utility."""
    pass


@cli.command()
@click.option("--detach", "-d", is_flag=True, help="Run the server in detached mode.")
@click.option("--no-sync", is_flag=True, help="Skip cloud synchronization before starting.")
def start(detach: bool = False, no_sync: bool = False) -> None:
    """Start the Cheshire-Cat AI server."""
    # Check if Docker is available
    is_available, error_message = docker.check_docker_availability()
    if not is_available:
        click.echo(f"Error: {error_message}", err=True)
        raise SystemExit(1)

    app_dir = _ensure_app_directory()

    # Perform cloud sync before starting if enabled
    if not no_sync:
        sync_manager = SyncManager(app_dir)
        if sync_manager.is_enabled():
            click.echo("Synchronizing with cloud storage...")
            if sync_manager.sync(app_dir, ""):
                click.echo("✓ Cloud sync completed successfully")
            else:
                click.echo("⚠ Warning: Cloud sync failed, continuing anyway...", err=True)

    os.chdir(app_dir)
    cmd = ["docker", "compose", "up"]
    if detach:
        cmd.append("-d")
    os.execvp("docker", cmd)


@cli.command()
@click.option("--no-sync", is_flag=True, help="Skip cloud synchronization after stopping.")
def stop(no_sync: bool = False) -> None:
    """Stop the Cheshire-Cat AI server."""
    # Check if Docker is available
    is_available, error_message = docker.check_docker_availability()
    if not is_available:
        click.echo(f"Error: {error_message}", err=True)
        raise SystemExit(1)

    app_dir = _ensure_app_directory()

    os.chdir(app_dir)

    # Stop the server
    result = subprocess.run(
        ["docker", "compose", "stop"],
        capture_output=True,
        text=True
    )

    if result.returncode != 0:
        click.echo(f"Error stopping server: {result.stderr}", err=True)
        raise SystemExit(1)

    click.echo("Server stopped successfully")

    # Perform cloud sync after stopping if enabled
    if not no_sync:
        sync_manager = SyncManager(app_dir)
        if sync_manager.is_enabled():
            click.echo("Synchronizing with cloud storage...")
            if sync_manager.sync(app_dir, ""):
                click.echo("✓ Cloud sync completed successfully")
            else:
                click.echo("⚠ Warning: Cloud sync failed", err=True)


@cli.command()
def update() -> None:
    """Update the Cheshire-Cat AI server."""
    # Check if Docker is available
    is_available, error_message = docker.check_docker_availability()
    if not is_available:
        click.echo(f"Error: {error_message}", err=True)
        raise SystemExit(1)

    app_dir = _ensure_app_directory()

    os.chdir(app_dir)
    os.execvp("docker", ["docker", "pull", "ghcr.io/cheshire-cat-ai/core"])


@cli.group()
def sync() -> None:
    """Manage cloud synchronization settings."""
    pass


@sync.command(name="configure")
@click.argument("provider", type=click.Choice(["webdav"], case_sensitive=False))
@click.option("--url", prompt=True, help="WebDAV server URL")
@click.option("--username", prompt=True, help="Username for authentication")
@click.option("--password", prompt=True, hide_input=True, help="Password for authentication")
@click.option("--remote-path", default="/ccat", help="Remote path for synchronization")
def sync_configure(provider: str, url: str, username: str, password: str, remote_path: str) -> None:
    """Configure cloud synchronization."""
    app_dir = _ensure_app_directory()
    sync_manager = SyncManager(app_dir)

    click.echo(f"Configuring {provider} provider...")

    config = {
        "url": url,
        "username": username,
        "password": password,
        "remote_path": remote_path,
    }

    if sync_manager.configure(provider, config):
        click.echo(f"✓ Successfully configured {provider} synchronization")
        click.echo("Cloud sync will now run automatically when starting/stopping the server")
    else:
        click.echo(f"✗ Failed to configure {provider} synchronization", err=True)
        click.echo("Please check your settings and try again", err=True)
        raise SystemExit(1)


@sync.command(name="disable")
def sync_disable() -> None:
    """Disable cloud synchronization."""
    app_dir = _ensure_app_directory()
    sync_manager = SyncManager(app_dir)

    sync_manager.disable()
    click.echo("✓ Cloud synchronization disabled")


@sync.command(name="status")
def sync_status() -> None:
    """Show cloud synchronization status."""
    app_dir = _ensure_app_directory()
    sync_manager = SyncManager(app_dir)

    config_info = sync_manager.get_config_info()

    if config_info["enabled"]:
        click.echo("Cloud synchronization: ENABLED")
        click.echo(f"Provider: {config_info['provider']}")
        click.echo("Configuration:")
        for key, value in config_info["config"].items():
            click.echo(f"  {key}: {value}")
    else:
        click.echo("Cloud synchronization: DISABLED")
        click.echo("\nTo enable, run: ccat sync configure <provider>")


@sync.command(name="now")
def sync_now() -> None:
    """Manually trigger cloud synchronization."""
    app_dir = _ensure_app_directory()
    sync_manager = SyncManager(app_dir)

    if not sync_manager.is_enabled():
        click.echo("Cloud synchronization is not enabled", err=True)
        click.echo("Run 'ccat sync configure' to set it up", err=True)
        raise SystemExit(1)

    click.echo("Synchronizing with cloud storage...")
    if sync_manager.sync(app_dir, ""):
        click.echo("✓ Cloud sync completed successfully")
    else:
        click.echo("✗ Cloud sync failed", err=True)
        raise SystemExit(1)
