"""Configuration loading from config.json and .env with validation."""

from __future__ import annotations

import json
import os
from dataclasses import dataclass, field
from pathlib import Path

from dotenv import load_dotenv

PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent


@dataclass
class SiteConfig:
    property_url: str
    display_name: str
    sitemap_urls: list[str]


@dataclass
class KPIThresholds:
    min_clicks: int
    min_impressions: int
    min_ctr: float
    max_position: float
    min_index_rate: float


@dataclass
class EmailConfig:
    smtp_host: str = ""
    smtp_port: int = 587
    smtp_user: str = ""
    smtp_password: str = ""
    email_from: str = ""
    email_to: list[str] = field(default_factory=list)
    sendgrid_api_key: str = ""
    sendgrid_from: str = ""

    @property
    def use_sendgrid(self) -> bool:
        return bool(self.sendgrid_api_key)


@dataclass
class Settings:
    sites: list[SiteConfig]
    kpi_thresholds: KPIThresholds
    tracked_keywords: list[str]
    keyword_alert_threshold: int
    url_inspection_sample_size: int
    execution_timeout_hours: int
    max_sitemap_resubmit_retries: int
    service_account_key_path: str
    email: EmailConfig


def load_settings(
    config_path: str | None = None,
    env_path: str | None = None,
) -> Settings:
    """Load and validate settings from config.json and .env."""
    if env_path is None:
        env_path = str(PROJECT_ROOT / ".env")
    load_dotenv(env_path)

    if config_path is None:
        config_path = str(PROJECT_ROOT / "config.json")

    with open(config_path, "r", encoding="utf-8") as f:
        cfg = json.load(f)

    # Validate required sections
    for key in ("sites", "kpi_thresholds", "tracked_keywords"):
        if key not in cfg:
            raise ValueError(f"Missing required config key: {key}")

    sites = [
        SiteConfig(
            property_url=s["property_url"],
            display_name=s["display_name"],
            sitemap_urls=s.get("sitemap_urls", []),
        )
        for s in cfg["sites"]
    ]
    if not sites:
        raise ValueError("At least one site must be configured")

    kt = cfg["kpi_thresholds"]
    kpi_thresholds = KPIThresholds(
        min_clicks=kt["min_clicks"],
        min_impressions=kt["min_impressions"],
        min_ctr=kt["min_ctr"],
        max_position=kt["max_position"],
        min_index_rate=kt["min_index_rate"],
    )

    # Service account key path
    sa_key_path = os.getenv(
        "GOOGLE_SERVICE_ACCOUNT_KEY_PATH",
        str(PROJECT_ROOT / "credentials" / "service_account.json"),
    )

    # Email config from environment
    email_to_raw = os.getenv("EMAIL_TO", "")
    email_to = [e.strip() for e in email_to_raw.split(",") if e.strip()]

    email = EmailConfig(
        smtp_host=os.getenv("SMTP_HOST", "smtp.gmail.com"),
        smtp_port=int(os.getenv("SMTP_PORT", "587")),
        smtp_user=os.getenv("SMTP_USER", ""),
        smtp_password=os.getenv("SMTP_PASSWORD", ""),
        email_from=os.getenv("EMAIL_FROM", ""),
        email_to=email_to,
        sendgrid_api_key=os.getenv("SENDGRID_API_KEY", ""),
        sendgrid_from=os.getenv("SENDGRID_FROM", ""),
    )

    return Settings(
        sites=sites,
        kpi_thresholds=kpi_thresholds,
        tracked_keywords=cfg.get("tracked_keywords", []),
        keyword_alert_threshold=cfg.get("keyword_alert_threshold", 3),
        url_inspection_sample_size=cfg.get("url_inspection_sample_size", 50),
        execution_timeout_hours=cfg.get("execution_timeout_hours", 3),
        max_sitemap_resubmit_retries=cfg.get("max_sitemap_resubmit_retries", 3),
        service_account_key_path=sa_key_path,
        email=email,
    )
