"""BackgroundJobs feature codegen for NIKAME.

Provides Celery/Redis background worker support.
"""

from __future__ import annotations

from nikame.codegen.base import BaseCodegen
from nikame.codegen.registry import register_codegen


@register_codegen
class JobsCodegen(BaseCodegen):
    """Generates celery worker and tasks code."""

    NAME = "background_jobs"
    DESCRIPTION = "Celery worker and Beat scheduler"
    DEPENDENCIES: list[str] = []
    MODULE_DEPENDENCIES: list[str] = ["redis"]

    def generate(self) -> list[tuple[str, str]]:
        """Generate Celery worker and tasks."""
        files: list[tuple[str, str]] = []
        
        celery_app_py = '''"""
Celery worker configuration.
Generated by NIKAME.
"""

from celery import Celery
from app.core.config import settings

broker_url = settings.CACHE_URL or "redis://localhost:6379/0"

worker = Celery(
    "nikame-worker",
    broker=broker_url,
    backend=broker_url,
    include=["app.tasks.system_tasks"]
)

worker.conf.update(
    task_serializer="json",
    accept_content=["json"],
    result_serializer="json",
    timezone="UTC",
    enable_utc=True,
    task_acks_late=True,
    worker_prefetch_multiplier=1,
)

if __name__ == "__main__":
    worker.start()
'''
        files.append(("app/core/worker.py", celery_app_py))

        files.append(("app/tasks/__init__.py", ""))
        
        system_tasks_py = '''"""System background tasks."""
from app.core.worker import worker

@worker.task(name="system.cleanup")
def cleanup_temp_files():
    """Example system cleanup task."""
    return "Cleanup complete"
'''
        files.append(("app/tasks/system_tasks.py", system_tasks_py))
        return files
