"""
Database-backed job manager for the API.

When a database URL is configured, the API uses this manager so jobs
are stored in the validation_jobs table and processed by worker processes.
"""

from __future__ import annotations

from typing import Any

from pycharter.worker.job_sources.database import DatabaseJobSource
from pycharter.worker.models import ValidationJob


class DatabaseJobManager:
    """Job manager that delegates to DatabaseJobSource (same interface for API)."""

    def __init__(self, db_url: str) -> None:
        self._db_url = db_url
        self._source: DatabaseJobSource | None = None

    def _get_source(self) -> DatabaseJobSource:
        if self._source is None:
            self._source = DatabaseJobSource(self._db_url, config=None)
        return self._source

    async def get_job_async(self, job_id: str) -> dict[str, Any]:
        return await self._get_source().get_job(job_id)

    async def list_jobs_async(
        self,
        status: str | None = None,
        limit: int | None = None,
        offset: int = 0,
    ) -> list[dict[str, Any]]:
        return await self._get_source().list_jobs(
            status=status, limit=limit, offset=offset
        )

    async def get_stats_async(self) -> dict[str, int]:
        return await self._get_source().get_stats()

    async def cancel_job_async(self, job_id: str) -> bool:
        return await self._get_source().cancel_job(job_id)

    async def delete_job_async(self, job_id: str) -> bool:
        return await self._get_source().delete_job(job_id)

    async def submit_job_async(
        self,
        contract_name: str,
        contract_version: str,
        data_source: str,
        options: dict[str, Any] | None = None,
        job_id: str | None = None,
        idempotency_key: str | None = None,
    ) -> str:
        source = self._get_source()
        job = ValidationJob(
            contract_name=contract_name,
            contract_version=contract_version,
            data_source=data_source,
            options=options,
            job_id=job_id,
            idempotency_key=idempotency_key or job_id,
        )
        return await source.submit(job)
