from dataclasses import dataclass, field, asdict
from datetime import datetime
from typing import Optional


@dataclass
class EPGEntry:
    """Represents a single EPG (Electronic Program Guide) entry."""
    title: str
    image: str
    channel: str
    start: str  # ISO 8601 format with timezone
    end: str    # ISO 8601 format with timezone
    description: str = ""
    category: str = ""

    def to_dict(self) -> dict:
        """Convert to the output JSON format."""
        result = {
            "title": self.title,
            "image": self.image,
            "channel": self.channel,
            "start": self.start,
            "end": self.end,
        }
        # Include optional fields only if they have values
        if self.description:
            result["description"] = self.description
        if self.category:
            result["category"] = self.category
        return result

    @staticmethod
    def format_datetime_iso(dt: datetime) -> str:
        """Format a datetime object to ISO 8601 string with timezone offset."""
        if dt.tzinfo is None:
            # Assume Europe/Rome timezone if none specified
            from zoneinfo import ZoneInfo
            dt = dt.replace(tzinfo=ZoneInfo("Europe/Rome"))
        return dt.isoformat()

    @staticmethod
    def epoch_ms_to_iso(epoch_ms: int) -> str:
        """Convert epoch milliseconds to ISO 8601 string with Rome timezone."""
        from zoneinfo import ZoneInfo
        dt = datetime.fromtimestamp(epoch_ms / 1000, tz=ZoneInfo("Europe/Rome"))
        return dt.isoformat()
