"""Worker infrastructure generator.

Generates deployment files for Hetzner Cloud background worker VMs,
including:

1. **Docker Compose** for worker services (local dev + production)
2. **GitHub Actions workflow** for deploying workers to Hetzner
3. **Cloud-init templates** for bootstrapping worker VMs
"""

from __future__ import annotations

from pathlib import Path

from jinja2 import Environment, PackageLoader, select_autoescape

from prisme.generators.base import GeneratedFile, GeneratorBase
from prisme.spec.stack import FileStrategy


class WorkerGenerator(GeneratorBase):
    """Generate worker infrastructure from ProjectSpec.workers."""

    def generate_files(self) -> list[GeneratedFile]:
        project_spec = self.context.project_spec
        if project_spec is None or project_spec.workers is None:
            return []

        workers = project_spec.workers
        if not workers.enabled or not workers.jobs:
            return []

        env = Environment(
            loader=PackageLoader("prisme", "templates/jinja2"),
            autoescape=select_autoescape(),
            trim_blocks=True,
            lstrip_blocks=True,
        )

        files: list[GeneratedFile] = []

        # Worker docker-compose (for local dev and production)
        template = env.get_template("deploy/hetzner/workers/docker-compose.workers.yml.jinja2")
        content = template.render(
            project_name=project_spec.name,
            project_name_snake=project_spec.name.replace("-", "_"),
            jobs=workers.jobs,
            docker_registry=workers.docker_registry,
        )
        files.append(
            GeneratedFile(
                path=Path("docker-compose.workers.yml"),
                content=content,
                strategy=FileStrategy.GENERATE_ONCE,
                description="Worker docker-compose",
            )
        )

        # Worker deployment workflow
        template = env.get_template("deploy/hetzner/workers/deploy-workers.yml.jinja2")
        content = template.render(
            project_name=project_spec.name,
            jobs=workers.jobs,
            default_server_type=workers.default_server_type,
            default_location=workers.default_location,
            docker_registry=workers.docker_registry,
        )
        files.append(
            GeneratedFile(
                path=Path(".github/workflows/deploy-workers.yml"),
                content=content,
                strategy=FileStrategy.GENERATE_ONCE,
                description="Worker deploy workflow",
            )
        )

        return files
