from __future__ import annotations

from enum import Enum
from typing import Literal

from pydantic import BaseModel, ConfigDict, field_validator

from services.export_query import ProjectExportFilters, ScenarioExportFilters


class ExportFormat(str, Enum):
    CSV = "csv"
    XLSX = "xlsx"


class BaseExportRequest(BaseModel):
    format: ExportFormat = ExportFormat.CSV
    include_metadata: bool = False

    model_config = ConfigDict(extra="forbid")


class ProjectExportRequest(BaseExportRequest):
    filters: ProjectExportFilters | None = None

    @field_validator("filters", mode="before")
    @classmethod
    def validate_filters(cls, value: ProjectExportFilters | None) -> ProjectExportFilters | None:
        if value is None:
            return None
        if isinstance(value, ProjectExportFilters):
            return value
        return ProjectExportFilters(**value)


class ScenarioExportRequest(BaseExportRequest):
    filters: ScenarioExportFilters | None = None

    @field_validator("filters", mode="before")
    @classmethod
    def validate_filters(cls, value: ScenarioExportFilters | None) -> ScenarioExportFilters | None:
        if value is None:
            return None
        if isinstance(value, ScenarioExportFilters):
            return value
        return ScenarioExportFilters(**value)


class ExportTicket(BaseModel):
    token: str
    format: ExportFormat
    resource: Literal["projects", "scenarios"]

    model_config = ConfigDict(extra="forbid")


class ExportResponse(BaseModel):
    ticket: ExportTicket

    model_config = ConfigDict(extra="forbid")


__all__ = [
    "ExportFormat",
    "ProjectExportRequest",
    "ScenarioExportRequest",
    "ExportTicket",
    "ExportResponse",
]
