import os
from dataclasses import dataclass
from pathlib import Path


def _parse_bool(val: str, default: bool = False) -> bool:
    if val is None:
        return default
    return val.strip().lower() in {"1", "true", "yes", "y", "on"}


def load_env_file(env_path: Path) -> None:
    """
    Minimal .env loader (no extra dependency).
    Supports lines like KEY=VALUE, ignores # comments and blank lines.
    Won't override existing environment variables.
    """
    if not env_path.exists():
        return

    for raw in env_path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        if "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip("'").strip('"')
        if key and key not in os.environ:
            os.environ[key] = value


@dataclass(frozen=True)
class Settings:
    # API auth
    api_key: str
    api_id: str
    api_version: str

    # network
    api_timeout: int
    max_retries: int

    # output
    output_dir: str
    output_timezone: str

    # pacing
    sleep_between_pages: float
    sleep_between_orders: float
    sleep_between_events: float

    # naming
    include_event_id_in_xlsx_name: bool

    # default
    default_event_id: int

    # columns
    hidden_columns: set
    output_columns: list


def get_settings() -> Settings:
    # Load .env from project root (same folder as this file)
    root = Path(__file__).resolve().parent
    load_env_file(root / ".env")

    hidden_columns = {'ticket_id', 'ticket_type', 'ticket_type_id', 'price', 'discount'}
    output_columns = [
        'title', 'date', 'order_id', 'table', 'seat', 'table_seats_count',
        'sum', 'full_amount', 'name', 'phone', 'email'
    ]

    api_key = os.environ.get("RADARIO_API_KEY", "").strip()
    api_id = os.environ.get("RADARIO_API_ID", "711").strip()
    api_version = os.environ.get("RADARIO_API_VERSION", "1.1").strip()

    if not api_key:
        raise RuntimeError(
            "RADARIO_API_KEY is not set. Put it in .env (see .env.example) "
            "or export it as an environment variable."
        )

    return Settings(
        api_key=api_key,
        api_id=api_id,
        api_version=api_version,
        api_timeout=int(os.environ.get("API_TIMEOUT", "30")),
        max_retries=int(os.environ.get("MAX_RETRIES", "3")),
        output_dir=os.environ.get("OUTPUT_DIR", "data"),
        output_timezone=os.environ.get("OUTPUT_TIMEZONE", "Europe/Moscow"),
        sleep_between_pages=float(os.environ.get("SLEEP_BETWEEN_PAGES", "0.3")),
        sleep_between_orders=float(os.environ.get("SLEEP_BETWEEN_ORDERS", "0.2")),
        sleep_between_events=float(os.environ.get("SLEEP_BETWEEN_EVENTS", "0.5")),
        include_event_id_in_xlsx_name=_parse_bool(os.environ.get("INCLUDE_EVENT_ID_IN_XLSX_NAME"), True),
        default_event_id=int(os.environ.get("DEFAULT_EVENT_ID", "2600682")),
        hidden_columns=hidden_columns,
        output_columns=output_columns,
    )


def build_headers(s: Settings) -> dict:
    return {
        "api-key": s.api_key,
        "api-id": s.api_id,
        "api-version": s.api_version,
    }

