"""DTOs for audio transcription with FileBackedDTO support for zero-copy transfer"""

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

# %% auto #0
__all__ = ['AudioData', 'TranscriptionResult']

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

import numpy as np
import soundfile as sf

from cjm_plugin_system.core.interface import FileBackedDTO

# %% ../nbs/core.ipynb #c9970cdf
@dataclass
class AudioData:
    """
    Container for raw audio data.
    Implements FileBackedDTO for zero-copy transfer between Host and Worker processes.
    """
    samples: np.ndarray  # Audio sample data as numpy array
    sample_rate: int     # Sample rate in Hz (e.g., 16000, 44100)

    def to_temp_file(self) -> str: # Absolute path to temporary WAV file
        """Save audio to a temp file for zero-copy transfer to Worker process."""
        # Create temp file (delete=False so Worker can read it)
        tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
        
        # Ensure float32 format
        audio = self.samples
        if audio.dtype != np.float32:
            audio = audio.astype(np.float32)
        
        # Normalize if needed
        max_val = np.abs(audio).max()
        if max_val > 1.0:
            audio = audio / max_val
        
        # Write to disk
        sf.write(tmp.name, audio, self.sample_rate)
        tmp.close()
        
        return str(Path(tmp.name).absolute())

    def to_dict(self) -> Dict[str, Any]: # Serialized representation
        """Convert to dictionary for smaller payloads."""
        return {
            "samples": self.samples.tolist(),
            "sample_rate": self.sample_rate
        }
    
    @classmethod
    def from_file(
        cls,
        filepath: str # Path to audio file
    ) -> "AudioData": # AudioData instance
        """Load audio from a file."""
        samples, sample_rate = sf.read(filepath, dtype='float32')
        return cls(samples=samples, sample_rate=sample_rate)

# %% ../nbs/core.ipynb #dc1c53ac
@dataclass
class TranscriptionResult:
    """Standardized output for all transcription plugins."""
    text: str                                        # The transcribed text
    confidence: Optional[float] = None               # Overall confidence (0.0 to 1.0)
    segments: Optional[List[Dict[str, Any]]] = None  # Timestamped segments
    metadata: Dict[str, Any] = field(default_factory=dict)  # Additional metadata
