"""Pydantic models for Whisper Scribe."""

from pydantic import BaseModel
from enum import Enum
from typing import Optional, List
from datetime import datetime


class JobStatus(str, Enum):
    """Status of a transcription job."""
    PENDING = "pending"
    FETCHING_INFO = "fetching_info"
    DOWNLOADING = "downloading"
    CONVERTING = "converting"
    TRANSCRIBING = "transcribing"
    SAVING = "saving"
    COMPLETE = "complete"
    ERROR = "error"


class ExportFormat(str, Enum):
    """Available export formats."""
    TXT = "txt"
    SRT = "srt"
    VTT = "vtt"
    PDF = "pdf"
    MD = "md"


# Request/Response Models
class VideoPreviewRequest(BaseModel):
    url: str


class VideoPreview(BaseModel):
    url: str
    video_id: str
    title: str
    thumbnail: str
    duration: str
    channel: str


class TranscribeRequest(BaseModel):
    url: str


class QueueRequest(BaseModel):
    urls: List[str]


class TranscribeResponse(BaseModel):
    job_id: str
    status: JobStatus


class StatusResponse(BaseModel):
    status: JobStatus
    progress: int = 0
    message: Optional[str] = None
    stage: Optional[str] = None


class ResultResponse(BaseModel):
    text: str
    title: str
    file_path: Optional[str] = None
    language: Optional[str] = None
    text_direction: Optional[str] = None  # "rtl" or "ltr"


class CostEntry(BaseModel):
    """Single cost entry for an operation."""
    operation: str  # "transcription", "analysis", "qa", "resources"
    provider: str
    model: str
    cost_usd: float
    timestamp: str
    # Optional fields depending on operation type
    duration_seconds: Optional[float] = None  # For transcription
    input_tokens: Optional[int] = None  # For chat
    output_tokens: Optional[int] = None  # For chat
    total_tokens: Optional[int] = None  # For chat


class ItemCosts(BaseModel):
    """All costs associated with a history item."""
    entries: List[CostEntry] = []
    total_cost: float = 0.0


class QAEntry(BaseModel):
    """Single Q&A exchange."""
    question: str
    answer: str
    timestamp: str
    cost_info: Optional[CostEntry] = None
    references: Optional[dict] = None


class HistoryItem(BaseModel):
    id: str
    title: str
    url: str
    created_at: str
    file_path: str
    duration: Optional[str] = None
    thumbnail: Optional[str] = None
    language: Optional[str] = None
    text_direction: Optional[str] = None  # "rtl" or "ltr"


class FullHistoryItem(BaseModel):
    """Extended history item with all persisted data."""
    id: str
    title: str
    url: str
    created_at: str
    file_path: str
    duration: Optional[str] = None
    thumbnail: Optional[str] = None
    language: Optional[str] = None
    text_direction: Optional[str] = None  # "rtl" or "ltr"
    # Persisted data
    transcription: Optional[str] = None
    analysis: Optional[dict] = None
    qa_history: List[QAEntry] = []
    resources: Optional[dict] = None
    costs: ItemCosts = ItemCosts()
    topics: List[str] = []


class HistoryResponse(BaseModel):
    items: List[HistoryItem]
    total: int


class ExportRequest(BaseModel):
    format: ExportFormat


class QueueStatusResponse(BaseModel):
    queue: List[dict]
    current_job: Optional[str] = None
    total: int
    completed: int


class SettingsRequest(BaseModel):
    # API Keys
    openai_api_key: Optional[str] = None
    perplexity_api_key: Optional[str] = None
    anthropic_api_key: Optional[str] = None
    eden_api_key: Optional[str] = None
    # Provider selection
    transcription_provider: Optional[str] = None  # openai, eden
    analysis_provider: Optional[str] = None  # openai, anthropic, eden
    critique_provider: Optional[str] = None  # anthropic, openai, eden
    resources_provider: Optional[str] = None  # perplexity, eden
    # Output
    output_directory: Optional[str] = None


class SettingsResponse(BaseModel):
    # API Keys status
    openai_api_key_set: bool
    perplexity_api_key_set: bool
    anthropic_api_key_set: bool = False
    eden_api_key_set: bool = False
    # Provider selection
    transcription_provider: str = "openai"
    analysis_provider: str = "openai"
    critique_provider: str = "anthropic"
    resources_provider: str = "perplexity"
    # Output
    output_directory: str


class ValidateKeyResponse(BaseModel):
    valid: bool
    message: str


class UploadResponse(BaseModel):
    job_id: str
    status: JobStatus
    filename: str


class PlaylistVideo(BaseModel):
    video_id: str
    title: str
    thumbnail: Optional[str] = None
    duration: str
    url: str


class PlaylistPreview(BaseModel):
    playlist_id: str
    title: str
    channel: str
    video_count: int
    videos: List[PlaylistVideo]


class PlaylistRequest(BaseModel):
    url: str


class QARequest(BaseModel):
    question: str
    find_references: bool = True


class QAResponse(BaseModel):
    question: str
    transcription_answer: Optional[dict] = None
    references: Optional[dict] = None
    combined_analysis: Optional[str] = None
    references_error: Optional[str] = None


class CustomPromptAnalysisRequest(BaseModel):
    prompt_id: Optional[str] = None
    prompt_text: Optional[str] = None


class BookReferencesRequest(BaseModel):
    topic: str
