"""DTOs for media analysis and processing with FileBackedDTO support for zero-copy transfer"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/core.ipynb.

# %% auto #0
__all__ = ['TimeRange', 'MediaMetadata', 'MediaAnalysisResult']

# %% ../nbs/core.ipynb #d0dd18be
import json
import tempfile
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Any, Dict, List, Optional

from cjm_plugin_system.core.interface import FileBackedDTO

# %% ../nbs/core.ipynb #0283c341
@dataclass
class TimeRange:
    """Represents a temporal segment within a media file."""
    start: float                                    # Start time in seconds
    end: float                                      # End time in seconds
    label: str = "segment"                          # Segment type (e.g., 'speech', 'silence', 'scene')
    confidence: Optional[float] = None              # Detection confidence (0.0 to 1.0)
    payload: Dict[str, Any] = field(default_factory=dict)  # Extra data (e.g., speaker embedding)

    def to_dict(self) -> Dict[str, Any]:  # Serialized representation
        """Convert to dictionary for JSON serialization."""
        return asdict(self)

# %% ../nbs/core.ipynb #26ba8335
@dataclass
class MediaMetadata:
    """Container for media file metadata."""
    path: str                                                   # File path
    duration: float                                             # Duration in seconds
    format: str                                                 # Container format (e.g., 'mp4', 'mkv')
    size_bytes: int                                             # File size in bytes
    video_streams: List[Dict[str, Any]] = field(default_factory=list)  # Video stream info
    audio_streams: List[Dict[str, Any]] = field(default_factory=list)  # Audio stream info

    def to_dict(self) -> Dict[str, Any]:  # Serialized representation
        """Convert to dictionary for JSON serialization."""
        return asdict(self)

# %% ../nbs/core.ipynb #28583e91
@dataclass
class MediaAnalysisResult:
    """Standard output for media analysis plugins."""
    ranges: List[TimeRange]                              # Detected temporal segments
    metadata: Dict[str, Any] = field(default_factory=dict)  # Global analysis stats

    def to_temp_file(self) -> str:  # Absolute path to temporary JSON file
        """Save results to a temp JSON file for zero-copy transfer."""
        tmp = tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode='w')
        
        data = {
            "ranges": [r.to_dict() for r in self.ranges],
            "metadata": self.metadata
        }
        
        json.dump(data, tmp)
        tmp.close()
        return str(Path(tmp.name).absolute())
    
    @classmethod
    def from_file(
        cls,
        filepath: str  # Path to JSON file
    ) -> "MediaAnalysisResult":  # Loaded result instance
        """Load results from a JSON file."""
        with open(filepath, 'r') as f:
            data = json.load(f)
            
        ranges = [TimeRange(**r) for r in data.get('ranges', [])]
        return cls(ranges=ranges, metadata=data.get('metadata', {}))
