"""
Time-shift configuration loader.

Loads and validates time-shift configurations from YAML files or S3.
"""

import yaml
from pathlib import Path
from typing import Dict, Any
from ..models.time_shift_models import TimeShiftConfig


class TimeShiftConfigLoader:
    """
    Loads and validates time-shift configuration.

    Supports loading from local files or S3 paths.
    """

    def load_config(self, config_path: str) -> TimeShiftConfig:
        """
        Load time-shift configuration from file.

        Args:
            config_path: Path to YAML config file (local or S3)

        Returns:
            Validated TimeShiftConfig

        Raises:
            FileNotFoundError: If config file doesn't exist
            ValueError: If config format is invalid
            yaml.YAMLError: If YAML parsing fails

        Examples:
            >>> loader = TimeShiftConfigLoader()
            >>> config = loader.load_config("configs/time-shift-2026.yaml")
        """
        if config_path.startswith("s3://"):
            return self._load_from_s3(config_path)
        else:
            return self._load_from_file(config_path)

    def _load_from_file(self, file_path: str) -> TimeShiftConfig:
        """
        Load configuration from local YAML file.

        Args:
            file_path: Local file path

        Returns:
            TimeShiftConfig instance
        """
        path = Path(file_path)
        if not path.exists():
            raise FileNotFoundError(f"Config file not found: {file_path}")

        with open(path, 'r') as f:
            data = yaml.safe_load(f)

        return self._parse_config(data)

    def _load_from_s3(self, s3_path: str) -> TimeShiftConfig:
        """
        Load configuration from S3.

        Args:
            s3_path: S3 path (s3://bucket/key)

        Returns:
            TimeShiftConfig instance
        """
        import boto3

        # Parse S3 path
        parts = s3_path.replace("s3://", "").split("/", 1)
        bucket = parts[0]
        key = parts[1] if len(parts) > 1 else ""

        # Download and parse
        s3_client = boto3.client('s3')
        response = s3_client.get_object(Bucket=bucket, Key=key)
        content = response['Body'].read().decode('utf-8')
        data = yaml.safe_load(content)

        return self._parse_config(data)

    def _parse_config(self, data: Dict[str, Any]) -> TimeShiftConfig:
        """
        Parse raw config data into TimeShiftConfig.

        Args:
            data: Raw YAML data

        Returns:
            TimeShiftConfig instance

        Raises:
            ValueError: If required fields missing or invalid

        Note:
            S3 bucket is read from ~/.czbg/.env (CZBILLGEN_S3_BUCKET)
            S3 root folder is hard-coded as "piedpiper-custom-billing"
            These should NOT be in the config file.
        """
        if "time_shift_config" not in data:
            raise ValueError(
                "Config must contain 'time_shift_config' top-level key"
            )

        config_data = data["time_shift_config"]

        # Extract and validate fields
        # Note: s3_bucket and s3_root_folder removed - read from env/hard-coded
        config = TimeShiftConfig(
            source_month=config_data.get("source_month"),
            target_months=config_data.get("target_months"),
            target_range=config_data.get("target_range"),
            providers=config_data.get("providers", []),
            organizations=config_data.get("organizations", {})
        )

        # Validation happens in TimeShiftConfig.__post_init__
        return config
