"""AWS Batch infrastructure generator.

Generates Terraform/CloudFormation and GitHub Actions workflows for
AWS Batch job processing, including:

1. **Batch compute environment** (Fargate or EC2)
2. **Job queue** for scheduling jobs
3. **Job definitions** for each configured job
4. **EventBridge rules** for scheduled jobs
5. **GitHub Actions workflow** for deploying batch infrastructure
"""

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 BatchGenerator(GeneratorBase):
    """Generate AWS Batch infrastructure from ProjectSpec.batch."""

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

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

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

        files: list[GeneratedFile] = []

        # Terraform for AWS Batch infrastructure
        template = env.get_template("deploy/aws/batch/main.tf.jinja2")
        content = template.render(
            project_name=project_spec.name,
            project_name_snake=project_spec.name.replace("-", "_"),
            region=batch.region,
            compute_environment_name=batch.compute_environment_name
            or f"{project_spec.name}-batch-env",
            job_queue_name=batch.job_queue_name or f"{project_spec.name}-job-queue",
            max_vcpus=batch.max_vcpus,
            subnets=batch.subnets,
            security_groups=batch.security_groups,
            jobs=batch.jobs,
            docker_registry=project_spec.build.registry if project_spec.build else "ghcr.io",
        )
        files.append(
            GeneratedFile(
                path=Path("deploy/aws-batch/main.tf"),
                content=content,
                strategy=FileStrategy.GENERATE_ONCE,
                description="AWS Batch Terraform config",
            )
        )

        # GitHub Actions workflow for deploying batch infra
        template = env.get_template("deploy/aws/batch/deploy-batch.yml.jinja2")
        content = template.render(
            project_name=project_spec.name,
            region=batch.region,
            jobs=batch.jobs,
        )
        files.append(
            GeneratedFile(
                path=Path(".github/workflows/deploy-batch.yml"),
                content=content,
                strategy=FileStrategy.GENERATE_ONCE,
                description="AWS Batch deploy workflow",
            )
        )

        return files
