"""
Time-shift job submission service.

Submits time-shift jobs to the CZBG API.
"""

import yaml
from ..models.time_shift_models import TimeShiftConfig
from ...api.client import APIClient


class TimeShiftJobSubmitter:
    """Submits time-shift jobs to API."""

    def __init__(self, api_client: APIClient):
        """
        Initialize with API client dependency.

        Args:
            api_client: API client for job submission
        """
        self.api_client = api_client

    def submit_job(
        self,
        config: TimeShiftConfig,
        dataset_name: str
    ) -> str:
        """
        Submit time-shift job and return job_id.

        Args:
            config: Time-shift configuration
            dataset_name: Unique name for message_group_id (enables parallel processing)

        Returns:
            Job ID from API
        """
        config_yaml = self._serialize_config(config)

        job_id = self.api_client.submit_job(
            job_type="time_shift",
            config_content=config_yaml,
            dataset_name=dataset_name,
            description=f"Time-shift: {dataset_name}"
        )

        return job_id

    def _serialize_config(self, config: TimeShiftConfig) -> str:
        """
        Serialize config to YAML string.

        Converts TimeShiftConfig dataclass to YAML format expected by API.
        """
        config_dict = {
            "time_shift_config": {
                "source_month": config.source_month,
                "providers": config.providers,
                "organizations": config.organizations
            }
        }

        # Add target_months or target_range
        if config.target_months:
            config_dict["time_shift_config"]["target_months"] = config.target_months
        if config.target_range:
            config_dict["time_shift_config"]["target_range"] = config.target_range

        return yaml.dump(config_dict, default_flow_style=False)
