"""CLI commands: vscode start/stop/open/logs — manage VS Code Web service."""

from __future__ import annotations

import subprocess
import sys
import webbrowser

from proxym.config import get_settings


def _compose(*args: str) -> int:
    """Run docker compose with given arguments, return exit code."""
    cmd = ["docker", "compose", "--profile", "vscode", *args]
    result = subprocess.run(cmd, cwd=_find_compose_dir())
    return result.returncode


def _find_compose_dir() -> str:
    """Find the directory containing docker-compose.yml."""
    from pathlib import Path

    # Walk up from this file to find docker-compose.yml
    here = Path(__file__).resolve()
    for parent in here.parents:
        if (parent / "docker-compose.yml").exists():
            return str(parent)
    # Fallback: current working directory
    return "."


def cmd_vscode_start(args):
    """Start VS Code Web (docker compose --profile vscode up -d)."""
    print("Starting VS Code Web...")
    rc = _compose("up", "-d", "vscode")
    if rc == 0:
        settings = get_settings()
        print(f"✅ VS Code Web → http://localhost:{settings.vscode_port}")
    else:
        print("❌ Failed to start VS Code Web", file=sys.stderr)
        sys.exit(rc)


def cmd_vscode_stop(args):
    """Stop VS Code Web."""
    print("Stopping VS Code Web...")
    rc = _compose("stop", "vscode")
    if rc == 0:
        print("✅ VS Code Web stopped")
    else:
        print("❌ Failed to stop VS Code Web", file=sys.stderr)
        sys.exit(rc)


def cmd_vscode_open(args):
    """Open VS Code Web in the default browser."""
    settings = get_settings()
    url = f"http://localhost:{settings.vscode_port}"
    print(f"Opening {url} ...")
    webbrowser.open(url)


def cmd_vscode_logs(args):
    """Show VS Code Web logs (follows)."""
    _compose("logs", "-f", "--tail=100", "vscode")


def cmd_vscode_status(args):
    """Show VS Code Web container status."""
    _compose("ps", "vscode")


def cmd_vscode_build(args):
    """Rebuild VS Code Web image."""
    print("Building VS Code Web image...")
    rc = _compose("build", "--no-cache", "vscode")
    if rc == 0:
        print("✅ VS Code Web image rebuilt")
    else:
        print("❌ Build failed", file=sys.stderr)
        sys.exit(rc)
