"""
iq init command - Initialize new projects.
"""

from __future__ import annotations

import subprocess
import sys
import venv
from pathlib import Path

import click
from rich.console import Console

from iq_sdk.cli import (
    copy_template_dir,
    get_template_path,
    render_template,
)

# Use stderr for all user messages so stdout is clean for eval
console = Console(stderr=True)


def _is_dev_mode(target_path: Path) -> bool:
    """
    Check if we're creating a project in development mode.

    Dev mode is detected when the TARGET directory is inside a directory
    that already has a .venv (i.e., creating a sub-project within an
    existing Python project).

    Args:
        target_path: The resolved path where the project will be created
    """
    # Check if target is inside a directory with .venv
    for parent in target_path.parents:
        if (parent / ".venv").exists():
            return True
        # Stop at filesystem root or home
        if parent == Path.home() or parent == parent.parent:
            break

    return False


@click.command()
@click.argument("path", default=".", type=click.Path())
@click.option("--name", "-n", help="Name of the project (defaults to directory name)")
@click.option("--minimal", is_flag=True, help="Create minimal setup (no docker/devcontainer)")
@click.option(
    "--with-venv", "venv_mode", flag_value="with", help="Create project .venv and install iq-sdk"
)
@click.option(
    "--without-venv",
    "venv_mode",
    flag_value="without",
    help="Skip .venv creation (use parent venv)",
)
def init(path: str, name: str | None, minimal: bool, venv_mode: str | None) -> None:
    """
    Initialize a new iq-sdk project.

    \b
    Creates a complete project structure:
      config/settings.yml   Site and tool configuration
      .env                  Environment variables (passwords)
      .gitignore            Git ignore rules
      pyproject.toml        Project dependencies
      README.md             Documentation
      .devcontainer/        VS Code DevContainer
      .github/workflows/    GitHub Actions for Docker
      docker/               Dockerfile and docker-compose
      tools/                Your tool implementations

    \b
    Venv handling:
      --with-venv       Create project .venv and install iq-sdk
      --without-venv    Use parent venv (dev mode)
      (no flag)         Prompt, unless dev mode is detected
    """
    project_path = Path(path).resolve()

    # Determine if we should create a venv
    is_dev = _is_dev_mode(project_path)
    create_venv: bool

    if venv_mode == "with":
        create_venv = True
    elif venv_mode == "without":
        create_venv = False
    elif is_dev:
        # Dev mode: don't create venv, no prompt
        create_venv = False
        console.print("[dim]Dev mode detected - using parent venv[/dim]")
    else:
        # Not dev mode, no flag: prompt user
        create_venv = click.confirm(
            "Create a virtual environment (.venv) for this project?",
            default=True,
        )

    # Use directory name if no name provided
    if name is None:
        if project_path.name == ".":
            name = Path.cwd().name
        else:
            name = project_path.name

    if project_path.exists() and any(project_path.iterdir()):
        # Check if config/settings.yml already exists
        if (project_path / "config" / "settings.yml").exists():
            console.print(
                "[yellow]Project already initialized (config/settings.yml exists)[/yellow]"
            )
            if not click.confirm("Overwrite existing files?"):
                raise click.Abort()

    project_path.mkdir(parents=True, exist_ok=True)

    context = {
        "name": name,
        "name_snake": name.replace("-", "_").lower(),
        "version": "0.1.0",
    }

    console.print(f"[bold blue]Initializing project '{name}' in {project_path}[/bold blue]")

    # Create directories
    (project_path / "tools").mkdir(exist_ok=True)
    (project_path / "config").mkdir(exist_ok=True)
    (project_path / "docs").mkdir(exist_ok=True)

    # Create project marker file and register project
    from iq_sdk.cli.project import create_project_marker, set_active_project

    create_project_marker(project_path)

    # Copy project template (config/settings.yml, pyproject.toml, README.md, .gitignore, etc.)
    copy_template_dir("project", project_path, context)
    console.print("  [green]✓[/green] Project files created")

    # Create .env file with password placeholder
    env_content = """# iq-sdk Environment Variables
# This file contains secrets - NEVER commit to version control!

# Worker ID (optional, auto-derived from hostname)
# IQ_WORKER_ID=my-worker

# Site passwords
IQ_SITE_DEFAULT_PASSWORD=

# Add passwords for additional sites:
# IQ_SITE_PRODUCTION_PASSWORD=
# IQ_SITE_STAGING_PASSWORD=

# Or use file references (K8s/Docker secrets style):
# IQ_SITE_PRODUCTION_API_SECRET_FILE=/run/secrets/prod-password
#
# For JSON/YAML secrets, extract with _PASSWORD_KEY (dot-notation):
# IQ_SITE_PRODUCTION_API_SECRET_FILE=/etc/secrets/creds.json
# IQ_SITE_PRODUCTION_API_SECRET_KEY=database.password

# Custom environment variables (referenced in config/settings.yml)
# API_KEY=your-api-key
# DEBUG=true
"""
    (project_path / ".env").write_text(env_content)
    console.print("  [green]✓[/green] .env file created")

    if not minimal:
        # DevContainer
        copy_template_dir("devcontainer", project_path / ".devcontainer", context)
        console.print("  [green]✓[/green] DevContainer setup created")

        # Docker
        copy_template_dir("docker", project_path / "docker", context)
        console.print("  [green]✓[/green] Docker files created")

        # GitHub Actions
        (project_path / ".github" / "workflows").mkdir(parents=True, exist_ok=True)
        github_template = get_template_path("github")
        if github_template.exists():
            copy_template_dir("github", project_path / ".github", context)
        else:
            # Create inline if template doesn't exist
            docker_workflow_template = get_template_path("project") / "docker.yml.j2"
            if docker_workflow_template.exists():
                render_template(
                    docker_workflow_template,
                    project_path / ".github" / "workflows" / "docker.yml",
                    context,
                )
            else:
                # Fallback inline template
                docker_workflow = """name: Docker Build

on:
  push:
    branches: [main]
    tags: ["v*"]
  pull_request:
    branches: [main]

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install baker-cli
        run: pip install baker-cli

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Container Registry
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push
        if: github.event_name != 'pull_request'
        run: |
          baker build \\
            --check registry \\
            --push=on \\
            --targets all

      - name: Build (PR - no push)
        if: github.event_name == 'pull_request'
        run: |
          baker build \\
            --check local \\
            --push=off \\
            --targets all
"""
                (project_path / ".github" / "workflows" / "docker.yml").write_text(docker_workflow)
        console.print("  [green]✓[/green] GitHub Actions created")

    # Create project venv if requested
    if create_venv:
        venv_path = project_path / ".venv"
        console.print("  [dim]Creating virtual environment...[/dim]")

        # Create venv
        venv.create(venv_path, with_pip=True)

        # Determine pip path
        if sys.platform == "win32":
            pip_path = venv_path / "Scripts" / "pip"
        else:
            pip_path = venv_path / "bin" / "pip"

        # Install iq-sdk
        console.print("  [dim]Installing iq-sdk...[/dim]")
        result = subprocess.run(
            [str(pip_path), "install", "iq-sdk"],
            capture_output=True,
            text=True,
        )

        if result.returncode == 0:
            console.print("  [green]✓[/green] Virtual environment created with iq-sdk")
        else:
            console.print("  [green]✓[/green] Virtual environment created")
            console.print("  [yellow]⚠[/yellow] pip install iq-sdk failed (not yet on PyPI?)")
            console.print("    [dim]Install manually: pip install iq-sdk[/dim]")

    # Activate the project
    set_active_project(project_path)

    console.print(f"\n[bold green]✓ Project '{name}' initialized successfully![/bold green]")
    console.print(f"[green]Activated:[/green] {project_path}")

    if create_venv:
        console.print("\n[bold]Next steps:[/bold]")
        console.print(f"  1. cd {project_path}")
        console.print("  2. source .venv/bin/activate")
        console.print("  3. Edit .env and set IQ_SITE_DEFAULT_PASSWORD")
        console.print("  4. iq tool create my-tool")
        console.print("  5. iq worker start")
    else:
        console.print("\n[bold]Next steps:[/bold]")
        console.print(f"  1. cd {project_path}")
        console.print("  2. Edit .env and set IQ_SITE_DEFAULT_PASSWORD")
        console.print("  3. iq tool create my-tool")
        console.print("  4. iq worker start")
    console.print("\n[dim]For more: iq --help[/dim]")
