"""Job Processor - Routes jobs to appropriate services"""
from datetime import datetime
from app.database import SessionLocal
from app.models.job import Job
from app.services import (
    image_generator,
    image_upscaler,
    background_remover,
    video_generator,
    video_upscaler,
    subtitle_processor,
    voice_to_text,
    text_to_speech,
    alt_text_generator
)


async def process_job(job_id: str):
    """Process a job based on its module and action"""
    db = SessionLocal()
    try:
        job = db.query(Job).filter(Job.id == job_id).first()
        if not job:
            return

        # Update status
        job.status = "processing"
        job.started_at = datetime.utcnow()
        db.commit()

        try:
            # Route to appropriate service
            module = job.module
            action = job.action

            if module == "image_generator":
                await image_generator.generate(job_id)
            elif module == "image_upscaler":
                await image_upscaler.upscale(job_id)
            elif module == "background_remover":
                await background_remover.remove_background(job_id)
            elif module == "video_generator":
                await video_generator.generate(job_id)
            elif module == "video_upscaler":
                await video_upscaler.upscale(job_id)
            elif module == "subtitle_processor":
                await subtitle_processor.process(job_id)
            elif module == "voice_to_text":
                await voice_to_text.transcribe(job_id)
            elif module == "text_to_speech":
                if action == "synthesize":
                    await text_to_speech.synthesize(job_id)
                elif action == "convert":
                    await text_to_speech.speech_to_speech(job_id)
            elif module == "alt_text_generator":
                await alt_text_generator.generate(job_id)
            else:
                raise ValueError(f"Unknown module: {module}")

            # Mark as completed
            job.status = "completed"
            job.progress = 100
            job.completed_at = datetime.utcnow()
            db.commit()

        except Exception as e:
            job.status = "failed"
            job.error_message = str(e)
            job.completed_at = datetime.utcnow()
            db.commit()

    finally:
        db.close()
