"""
Manifest manager for time-shifting operations.

Handles reading and writing manifest.json files in CloudZero format.
"""

import json
import boto3
from typing import Dict, Any


class ManifestManager:
    """
    Manages manifest.json files for drops.

    Reads source manifests to get active drop IDs and creates CloudZero-format
    manifests for time-shifted target drops.
    """

    def __init__(self, s3_bucket: str):
        """
        Initialize manifest manager.

        Args:
            s3_bucket: S3 bucket name
        """
        self.s3_bucket = s3_bucket
        self.s3_client = boto3.client('s3')

    def read_manifest(self, s3_key: str) -> Dict[str, Any]:
        """
        Read manifest.json from S3.

        Args:
            s3_key: S3 key to manifest.json file

        Returns:
            Manifest data as dictionary

        Raises:
            RuntimeError: If manifest not found or invalid JSON
        """
        try:
            response = self.s3_client.get_object(
                Bucket=self.s3_bucket,
                Key=s3_key
            )
            content = response['Body'].read().decode('utf-8')
            return json.loads(content)
        except Exception as e:
            raise RuntimeError(
                f"Failed to read manifest from s3://{self.s3_bucket}/{s3_key}: "
                f"{str(e)}"
            )

    def write_manifest(
        self,
        s3_key: str,
        manifest_data: Dict[str, Any]
    ) -> None:
        """
        Write manifest.json to S3 in CloudZero format.

        Args:
            s3_key: S3 key for target manifest.json
            manifest_data: Manifest data (CloudZero format)

        Raises:
            RuntimeError: If write fails
        """
        try:
            content = json.dumps(manifest_data, indent=4)
            self.s3_client.put_object(
                Bucket=self.s3_bucket,
                Key=s3_key,
                Body=content.encode('utf-8'),
                ContentType='application/json'
            )
        except Exception as e:
            raise RuntimeError(
                f"Failed to write manifest to s3://{self.s3_bucket}/{s3_key}: "
                f"{str(e)}"
            )

    def create_manifest(self, drop_id: str) -> Dict[str, Any]:
        """
        Create CloudZero-format manifest data.

        Args:
            drop_id: Drop ID to reference in manifest

        Returns:
            Manifest data dictionary in CloudZero format
        """
        return {
            "version": "1.3.0",
            "current_drop_id": drop_id
        }
