"""Create a new algorithm service project."""

from __future__ import annotations

import shutil
import subprocess
import sys
from importlib import resources
from pathlib import Path

TEMPLATES = {
    "1": "basic",
    "2": "predict",
    "3": "cv",
    "basic": "basic",
    "predict": "predict",
    "cv": "cv",
}

TEMPLATE_DESCRIPTIONS = {
    "basic": "Minimal service skeleton",
    "predict": "Prediction/ML with pandas",
    "cv": "Computer vision with Pillow",
}

TEMPLATE_DEPS = {
    "basic": ["requests"],
    "predict": ["pandas", "requests"],
    "cv": ["opencv-python", "numpy", "requests"],
}


def select_template() -> str:
    """Prompt user to select a template interactively."""
    print("Select a template:")
    print(f"  1. basic   - {TEMPLATE_DESCRIPTIONS['basic']}")
    print(f"  2. predict - {TEMPLATE_DESCRIPTIONS['predict']}")
    print(f"  3. cv      - {TEMPLATE_DESCRIPTIONS['cv']}")

    while True:
        choice = input("Enter number or name [1]: ").strip() or "1"
        if choice in TEMPLATES:
            return TEMPLATES[choice]
        print(f"Invalid choice: {choice}. Please enter 1, 2, 3, basic, predict, or cv.")


def _pip_install(*args: str, capture: bool = True) -> subprocess.CompletedProcess:
    uv_path = shutil.which("uv")
    if uv_path:
        cmd = [uv_path, "pip", "install", *args]
    else:
        cmd = [sys.executable, "-m", "pip", "install", *args]
    return subprocess.run(cmd, capture_output=capture, text=True)


def install_stubs() -> bool:
    stubs_dir = resources.files("mas_algo_cli.stubs")
    try:
        with resources.as_file(stubs_dir) as stubs_path:
            result = _pip_install("-e", str(stubs_path))
            return result.returncode == 0
    except Exception:
        return False


def install_template_deps(template: str) -> bool:
    deps = TEMPLATE_DEPS.get(template, [])
    if not deps:
        return True
    try:
        result = _pip_install(*deps)
        return result.returncode == 0
    except Exception:
        return False


def execute(name: str, parent_dir: str, template: str | None = None) -> int:
    if "-" in name:
        print(f"Error: Project name '{name}' contains hyphens. Use underscores instead: {name.replace('-', '_')}")
        return 1

    parent = Path(parent_dir).resolve()
    project_dir = parent / name

    if project_dir.exists():
        print(f"Error: Directory '{project_dir}' already exists")
        return 1

    if template is None:
        template = select_template()

    print(f"Creating new algorithm service: {project_dir} (template: {template})")
    project_dir.mkdir(parents=True)

    template_dir = resources.files(f"mas_algo_cli.templates.{template}")

    for item in template_dir.iterdir():
        if item.is_file():
            content = item.read_text()
            content = content.replace("${name}", name)
            dest = project_dir / item.name
            dest.write_text(content)
            print(f"  Created: {item.name}")

    # Install stubs
    print(f"\nInstalling rest-stubs...")
    if install_stubs():
        print(f"  Installed: rest-stubs")
    else:
        print(f"  Warning: Failed to install rest-stubs")

    # Install template-specific dependencies
    deps = TEMPLATE_DEPS.get(template, [])
    if deps:
        print(f"Installing template dependencies: {', '.join(deps)}...")
        if install_template_deps(template):
            print(f"  Installed: {', '.join(deps)}")
        else:
            print(f"  Warning: Failed to install template dependencies")

    print(f"\nService created at: {project_dir}")
    print(f"\nNext steps:")
    print(f"  1. cd {name}")
    print(f"  2. cp .env.example .env")
    print(f"  3. Implement your algorithm in main.py")
    print(f"  4. algo run")
    print(f"  5. algo pack")

    return 0
