"""Built-in templates for the template gallery.

These templates are bundled with gaol and available
without network access.
"""

from __future__ import annotations

from typing import Any

# Built-in templates as dictionaries
# These are converted to Template objects by the loader
BUILTIN_TEMPLATES: dict[str, dict[str, Any]] = {
    # ==========================================================================
    # Web Development
    # ==========================================================================
    "web-dev/django": {
        "metadata": {
            "id": "web-dev/django",
            "display_name": "Django Development",
            "description": "Full Django development environment with PostgreSQL support",
            "category": "web-dev",
            "tags": ["python", "django", "web", "postgresql", "framework"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🐍",
        },
        "spec": {
            "name": "django-dev",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base", "dev-python"],
            "resources": {
                "memory": "2G",
                "cpus": 2,
            },
            "network": {
                "ports": ["8000:8000"],
            },
            "environment": {
                "DJANGO_DEBUG": "true",
                "DJANGO_SETTINGS_MODULE": "config.settings.local",
            },
            "volumes": ["~/projects:/workspace"],
            "working_dir": "/workspace",
        },
        "post_create_commands": [
            "uv pip install django psycopg2-binary django-debug-toolbar",
        ],
        "example_env": {
            "DATABASE_URL": "postgres://user:pass@localhost:5432/mydb",
            "SECRET_KEY": "your-secret-key-here",
            "DJANGO_DEBUG": "true",
        },
    },
    "web-dev/flask": {
        "metadata": {
            "id": "web-dev/flask",
            "display_name": "Flask Development",
            "description": "Lightweight Flask development environment",
            "category": "web-dev",
            "tags": ["python", "flask", "web", "api", "microframework"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🧪",
        },
        "spec": {
            "name": "flask-dev",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base", "dev-python"],
            "resources": {
                "memory": "1G",
                "cpus": 1,
            },
            "network": {
                "ports": ["5000:5000"],
            },
            "environment": {
                "FLASK_DEBUG": "1",
                "FLASK_APP": "app.py",
            },
            "volumes": ["~/projects:/workspace"],
            "working_dir": "/workspace",
        },
        "post_create_commands": [
            "uv pip install flask flask-sqlalchemy flask-migrate",
        ],
    },
    "web-dev/fastapi": {
        "metadata": {
            "id": "web-dev/fastapi",
            "display_name": "FastAPI Development",
            "description": "Modern async API development with FastAPI",
            "category": "web-dev",
            "tags": ["python", "fastapi", "api", "async", "openapi"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "⚡",
        },
        "spec": {
            "name": "fastapi-dev",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base", "dev-python"],
            "resources": {
                "memory": "2G",
                "cpus": 2,
            },
            "network": {
                "ports": ["8000:8000"],
            },
            "environment": {
                "PYTHONPATH": "/workspace",
            },
            "volumes": ["~/projects:/workspace"],
            "working_dir": "/workspace",
        },
        "post_create_commands": [
            "uv pip install 'fastapi[standard]' sqlalchemy alembic",
        ],
    },
    "web-dev/node": {
        "metadata": {
            "id": "web-dev/node",
            "display_name": "Node.js Development",
            "description": "Node.js development with pnpm and TypeScript",
            "category": "web-dev",
            "tags": ["node", "javascript", "typescript", "pnpm", "web"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🟢",
        },
        "spec": {
            "name": "node-dev",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base", "dev-node"],
            "resources": {
                "memory": "2G",
                "cpus": 2,
            },
            "network": {
                "ports": ["3000:3000", "5173:5173"],
            },
            "volumes": ["~/projects:/workspace"],
            "working_dir": "/workspace",
        },
        "post_create_commands": [
            "pnpm install -g typescript ts-node @types/node",
        ],
    },
    "web-dev/rails": {
        "metadata": {
            "id": "web-dev/rails",
            "display_name": "Ruby on Rails",
            "description": "Ruby on Rails development environment",
            "category": "web-dev",
            "tags": ["ruby", "rails", "web", "postgresql", "framework"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "💎",
        },
        "spec": {
            "name": "rails-dev",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base"],
            "resources": {
                "memory": "2G",
                "cpus": 2,
            },
            "network": {
                "ports": ["3000:3000"],
            },
            "environment": {
                "RAILS_ENV": "development",
            },
            "volumes": ["~/projects:/workspace"],
            "working_dir": "/workspace",
        },
        "post_create_commands": [
            "apt-get update && apt-get install -y ruby ruby-dev build-essential libpq-dev",
            "gem install rails bundler",
        ],
    },
    # ==========================================================================
    # Data Science
    # ==========================================================================
    "data-science/jupyter": {
        "metadata": {
            "id": "data-science/jupyter",
            "display_name": "Jupyter Lab",
            "description": "Jupyter Lab with data science packages",
            "category": "data-science",
            "tags": ["python", "jupyter", "pandas", "numpy", "matplotlib"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "📊",
        },
        "spec": {
            "name": "jupyter-lab",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base", "dev-python"],
            "resources": {
                "memory": "4G",
                "cpus": 2,
            },
            "network": {
                "ports": ["8888:8888"],
            },
            "volumes": ["~/notebooks:/workspace"],
            "working_dir": "/workspace",
        },
        "post_create_commands": [
            "uv pip install jupyterlab pandas numpy matplotlib seaborn scikit-learn",
        ],
        "readme": """# Jupyter Lab Template

Start Jupyter Lab with:
```bash
gaol exec jupyter-lab -- jupyter lab --ip=0.0.0.0 --no-browser
```

Then open http://localhost:8888 in your browser.
""",
    },
    "data-science/rstudio": {
        "metadata": {
            "id": "data-science/rstudio",
            "display_name": "RStudio Server",
            "description": "RStudio Server for R development",
            "category": "data-science",
            "tags": ["r", "rstudio", "statistics", "data-analysis"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "📈",
        },
        "spec": {
            "name": "rstudio",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base"],
            "resources": {
                "memory": "4G",
                "cpus": 2,
            },
            "network": {
                "ports": ["8787:8787"],
            },
            "volumes": ["~/r-projects:/home/rstudio"],
        },
        "post_create_commands": [
            "apt-get update && apt-get install -y r-base r-base-dev",
            "wget https://download2.rstudio.org/server/jammy/amd64/rstudio-server-2023.12.1-402-amd64.deb",
            "dpkg -i rstudio-server-*.deb || apt-get install -f -y",
            "rm rstudio-server-*.deb",
        ],
    },
    "data-science/mlflow": {
        "metadata": {
            "id": "data-science/mlflow",
            "display_name": "MLflow",
            "description": "MLflow for ML experiment tracking",
            "category": "data-science",
            "tags": ["python", "mlflow", "ml", "experiment-tracking"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🤖",
        },
        "spec": {
            "name": "mlflow",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base", "dev-python"],
            "resources": {
                "memory": "2G",
                "cpus": 2,
            },
            "network": {
                "ports": ["5000:5000"],
            },
            "volumes": ["~/mlruns:/mlruns"],
            "environment": {
                "MLFLOW_TRACKING_URI": "/mlruns",
            },
        },
        "post_create_commands": [
            "uv pip install mlflow scikit-learn pandas",
        ],
    },
    # ==========================================================================
    # DevOps
    # ==========================================================================
    "devops/kubernetes": {
        "metadata": {
            "id": "devops/kubernetes",
            "display_name": "Kubernetes Tools",
            "description": "kubectl, helm, and k9s for Kubernetes management",
            "category": "devops",
            "tags": ["kubernetes", "kubectl", "helm", "k9s", "devops"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "☸️",
        },
        "spec": {
            "name": "k8s-tools",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base"],
            "resources": {
                "memory": "1G",
                "cpus": 1,
            },
            "volumes": [
                "~/.kube:/root/.kube:ro",
                "~/k8s:/workspace",
            ],
            "working_dir": "/workspace",
        },
        "post_create_commands": [
            "curl -LO https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl && chmod +x kubectl && mv kubectl /usr/local/bin/",
            "curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash",
            "curl -sS https://webinstall.dev/k9s | bash",
        ],
    },
    "devops/terraform": {
        "metadata": {
            "id": "devops/terraform",
            "display_name": "Terraform",
            "description": "Terraform for infrastructure as code",
            "category": "devops",
            "tags": ["terraform", "iac", "infrastructure", "devops"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🏗️",
        },
        "spec": {
            "name": "terraform",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base"],
            "resources": {
                "memory": "1G",
                "cpus": 1,
            },
            "volumes": ["~/terraform:/workspace"],
            "working_dir": "/workspace",
        },
        "post_create_commands": [
            "apt-get update && apt-get install -y gnupg software-properties-common",
            "wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg",
            "echo 'deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com bookworm main' > /etc/apt/sources.list.d/hashicorp.list",
            "apt-get update && apt-get install -y terraform",
        ],
    },
    # ==========================================================================
    # Databases
    # ==========================================================================
    "database/postgres": {
        "metadata": {
            "id": "database/postgres",
            "display_name": "PostgreSQL",
            "description": "PostgreSQL database server with pgAdmin",
            "category": "database",
            "tags": ["postgresql", "database", "sql"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🐘",
        },
        "spec": {
            "name": "postgres",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base"],
            "resources": {
                "memory": "1G",
                "cpus": 1,
            },
            "network": {
                "ports": ["5432:5432"],
            },
            "environment": {
                "POSTGRES_USER": "postgres",
                "POSTGRES_DB": "postgres",
            },
            "volumes": ["~/pgdata:/var/lib/postgresql/data"],
        },
        "post_create_commands": [
            "apt-get update && apt-get install -y postgresql postgresql-contrib",
        ],
        "example_env": {
            "POSTGRES_PASSWORD": "your-secure-password",
        },
    },
    "database/redis": {
        "metadata": {
            "id": "database/redis",
            "display_name": "Redis",
            "description": "Redis in-memory data store",
            "category": "database",
            "tags": ["redis", "cache", "database", "key-value"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🔴",
        },
        "spec": {
            "name": "redis",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base"],
            "resources": {
                "memory": "512M",
                "cpus": 1,
            },
            "network": {
                "ports": ["6379:6379"],
            },
            "volumes": ["~/redis-data:/data"],
        },
        "post_create_commands": [
            "apt-get update && apt-get install -y redis-server",
        ],
    },
    # ==========================================================================
    # Gaming
    # ==========================================================================
    "gaming/steam": {
        "metadata": {
            "id": "gaming/steam",
            "display_name": "Steam",
            "description": "Steam gaming client with GPU support",
            "category": "gaming",
            "tags": ["steam", "gaming", "gpu"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🎮",
            "supported_runtimes": ["docker"],
        },
        "spec": {
            "name": "steam",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base", "gui"],
            "resources": {
                "memory": "8G",
                "cpus": 4,
            },
            "privileged": True,
        },
        "post_create_commands": [
            "dpkg --add-architecture i386",
            "apt-get update",
            "apt-get install -y steam-installer",
        ],
    },
    # ==========================================================================
    # Security
    # ==========================================================================
    "security/kali-tools": {
        "metadata": {
            "id": "security/kali-tools",
            "display_name": "Kali Tools",
            "description": "Common Kali Linux security tools",
            "category": "security",
            "tags": ["kali", "security", "pentesting", "tools"],
            "author": "gaol",
            "version": "1.0.0",
            "icon": "🔒",
        },
        "spec": {
            "name": "kali-tools",
            "runtime": "docker",
            "distro": "trixie",
            "profiles": ["base"],
            "resources": {
                "memory": "2G",
                "cpus": 2,
            },
            "network": {
                "mode": "host",
            },
            "privileged": True,
        },
        "post_create_commands": [
            "apt-get update && apt-get install -y nmap nikto sqlmap hydra john hashcat metasploit-framework",
        ],
    },
}


def get_builtin_template(template_id: str) -> dict[str, Any] | None:
    """Get a built-in template by ID.

    Args:
        template_id: Template ID (e.g., 'web-dev/django')

    Returns:
        Template dict or None if not found
    """
    return BUILTIN_TEMPLATES.get(template_id)


def list_builtin_templates() -> list[str]:
    """List all built-in template IDs.

    Returns:
        List of template IDs
    """
    return list(BUILTIN_TEMPLATES.keys())


def get_builtin_categories() -> set[str]:
    """Get all categories from built-in templates.

    Returns:
        Set of category names
    """
    categories = set()
    for template_id in BUILTIN_TEMPLATES:
        category = template_id.split("/")[0]
        categories.add(category)
    return categories
