"""
ChatGPT Automation Models

Pydantic models for structured responses and configuration.
Pattern follows JazzResponse from helix_cdc/jazz/jazz_http.py.
"""

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


def _detect_remote_session() -> str:
    """Detect if running in a remote control session."""
    if os.environ.get("CLAUDE_REMOTE_SESSION"):
        return "remote_control"
    if os.environ.get("CLAUDE_SESSION_TYPE") == "remote":
        return "remote_control"
    return "local"


class ChatGPTStatus(str, Enum):
    """Response status codes."""
    SUCCESS = "success"
    RATE_LIMITED = "rate_limited"
    SESSION_EXPIRED = "session_expired"
    DOM_CHANGED = "dom_changed"
    TIMEOUT = "timeout"
    ERROR = "error"


class StreamChunk(BaseModel):
    """Single chunk from streaming response."""
    text: str
    timestamp_ms: float
    chunk_index: int
    is_final: bool = False


class ChatGPTResponse(BaseModel):
    """Structured response from ChatGPT interaction.

    Includes timing metadata following JazzResponse pattern.
    """
    status: ChatGPTStatus
    text: str = ""
    chunks: List[StreamChunk] = Field(default_factory=list)

    # Timing
    ttft_ms: float = 0.0              # Time to first token
    total_time_ms: float = 0.0        # Total response time
    stream_duration_ms: float = 0.0   # Time from first to last chunk

    # Metadata
    timestamp: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
    model_detected: Optional[str] = None
    conversation_id: Optional[str] = None
    message_id: Optional[str] = None

    # Provenance: where did this request originate?
    source: str = Field(default_factory=_detect_remote_session)  # "local" | "remote_control"

    # Error info
    error_message: Optional[str] = None
    retry_after_seconds: Optional[int] = None


class ChatGPTClientConfig(BaseModel):
    """Configuration for ChatGPT browser client."""
    profile_path: Optional[str] = None
    headless: bool = False
    timeout_ms: int = 60000
    response_timeout_ms: int = 120000
    stream_poll_interval_ms: int = 100
