from __future__ import annotations

import json
from collections.abc import Mapping, Sequence
from datetime import UTC, date, datetime
from decimal import Decimal
from typing import cast

from sqlalchemy import MetaData, Table, create_engine, or_, select
from sqlalchemy.engine import Connection, Engine

from finops_batches.domain.models import BatchExecutionContext, Record
from finops_batches.providers.gcp.focus import GcpFocusTransformer


class GcpFocusBronzeExtractor:
    """Read GCP RAW Bronze and enrich it from the local billing-account reference."""

    def __init__(
        self,
        *,
        database_url: str,
        table_name: str = "gcp_billing_bronze",
        reference_table_name: str = "ref_gcp_billing_account",
    ) -> None:
        self._engine: Engine = create_engine(database_url, pool_pre_ping=True)
        metadata = MetaData()
        self._table = Table(table_name, metadata, autoload_with=self._engine)
        self._reference_table = Table(
            reference_table_name,
            metadata,
            autoload_with=self._engine,
        )

        required = {
            "id",
            "business_date",
            "payload",
            "source_hash",
            "ingestion_run_id",
            "page_number",
            "source_record_number",
            "api_version",
        }
        missing = sorted(required.difference(self._table.c.keys()))
        if missing:
            raise ValueError(
                f"Colonnes RAW Bronze absentes de {table_name!r}: " + ", ".join(missing)
            )

        reference_required = {
            "billing_account_id",
            "billing_account_name",
            "billing_account_name_source",
            "invoice_issuer_name",
            "invoice_issuer_source",
            "valid_from",
            "valid_to",
            "is_active",
        }
        reference_missing = sorted(
            reference_required.difference(self._reference_table.c.keys())
        )
        if reference_missing:
            raise ValueError(
                f"Colonnes de référence absentes de {reference_table_name!r}: "
                + ", ".join(reference_missing)
            )

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        table = self._table
        statement = (
            select(
                table.c.id.label("source_bronze_id"),
                table.c.business_date,
                table.c.payload,
                table.c.source_hash.label("source_payload_hash"),
                table.c.ingestion_run_id.label("source_ingestion_run_id"),
                table.c.page_number.label("source_page_number"),
                table.c.source_record_number,
                table.c.api_version.label("source_api_version"),
            )
            .where(table.c.business_date == context.business_date)
            .order_by(
                table.c.page_number,
                table.c.source_record_number,
                table.c.id,
            )
        )

        with self._engine.connect() as connection:
            rows = [dict(row) for row in connection.execute(statement).mappings()]

            billing_account_ids = {
                self._billing_account_id_from_payload(row.get("payload"))
                for row in rows
            }
            references = self._load_references(
                connection=connection,
                billing_account_ids=billing_account_ids,
                business_date=context.business_date,
            )

        result: list[Record] = []
        for row in rows:
            billing_account_id = self._billing_account_id_from_payload(
                row.get("payload")
            )
            reference = references.get(billing_account_id)
            row["reference_billing_account_name"] = (
                reference.get("billing_account_name") if reference is not None else None
            )
            row["reference_billing_account_name_source"] = (
                reference.get("billing_account_name_source")
                if reference is not None
                else None
            )
            row["reference_invoice_issuer_name"] = (
                reference.get("invoice_issuer_name") if reference is not None else None
            )
            row["reference_invoice_issuer_source"] = (
                reference.get("invoice_issuer_source")
                if reference is not None
                else None
            )
            result.append(cast(Record, row))

        return result

    def _load_references(
        self,
        *,
        connection: Connection,
        billing_account_ids: set[str],
        business_date: date,
    ) -> dict[str, Mapping[str, object]]:
        if not billing_account_ids:
            return {}

        table = self._reference_table
        statement = (
            select(
                table.c.billing_account_id,
                table.c.billing_account_name,
                table.c.billing_account_name_source,
                table.c.invoice_issuer_name,
                table.c.invoice_issuer_source,
                table.c.valid_from,
                table.c.valid_to,
            )
            .where(
                table.c.billing_account_id.in_(sorted(billing_account_ids)),
                table.c.valid_from <= business_date,
                or_(table.c.valid_to.is_(None), table.c.valid_to >= business_date),
                table.c.is_active.is_(True),
            )
            .order_by(
                table.c.billing_account_id,
                table.c.valid_from.desc(),
            )
        )

        references: dict[str, Mapping[str, object]] = {}
        for row in connection.execute(statement).mappings():
            mapping = cast(Mapping[str, object], row)
            billing_account_id = self._required_string(
                mapping.get("billing_account_id"),
                "ref_gcp_billing_account.billing_account_id",
            )
            if billing_account_id in references:
                raise ValueError(
                    "Plusieurs références GCP actives se chevauchent pour "
                    f"{billing_account_id!r} à la date {business_date.isoformat()}."
                )
            references[billing_account_id] = mapping

        return references

    @classmethod
    def _billing_account_id_from_payload(cls, value: object) -> str:
        payload = cls._json_object(value, "payload")
        return cls._required_string(
            payload.get("billing_account_id"),
            "billing_account_id",
        )

    def close(self) -> None:
        self._engine.dispose()

    @staticmethod
    def _json_object(value: object, field: str) -> dict[str, object]:
        if not isinstance(value, str):
            raise TypeError(f"{field} doit être une chaîne JSON.")

        try:
            decoded: object = json.loads(value)
        except json.JSONDecodeError as exc:
            raise ValueError(f"{field} n'est pas un JSON valide.") from exc

        if not isinstance(decoded, dict):
            raise TypeError(f"{field} doit contenir un objet JSON.")

        raw = cast(dict[object, object], decoded)
        result: dict[str, object] = {}
        for key, item in raw.items():
            if not isinstance(key, str):
                raise TypeError(f"Les clés de {field} doivent être des chaînes.")
            result[key] = item
        return result

    @staticmethod
    def _optional_string(value: object) -> str | None:
        if value is None:
            return None
        if isinstance(value, str):
            normalized = value.strip()
            return normalized or None
        if isinstance(value, (int, float, Decimal)) and not isinstance(value, bool):
            return str(value)
        raise TypeError(f"Valeur non convertible en chaîne: {type(value).__name__}.")

    @classmethod
    def _required_string(cls, value: object, field: str) -> str:
        result = cls._optional_string(value)
        if result is None:
            raise ValueError(f"{field} est obligatoire.")
        return result


class GcpFocusSilverTransformer:
    """Transform RAW GCP billing rows into the local FOCUS Silver schema."""

    NORMALIZATION_VERSION = "gcp-focus-silver-v3"

    _DB_DATETIME_FIELDS = (
        "BillingPeriodStart",
        "BillingPeriodEnd",
        "ChargePeriodStart",
        "ChargePeriodEnd",
        "x_ExportTime",
        "x_GeneratedAt",
    )

    def __init__(self, transformer: GcpFocusTransformer | None = None) -> None:
        self._transformer = transformer or GcpFocusTransformer()

    def transform(self, records: Sequence[Record]) -> list[Record]:
        generated_at = datetime.now(UTC)
        normalized_at = generated_at.replace(tzinfo=None)
        return [
            self._transform_one(
                record,
                generated_at=generated_at,
                normalized_at=normalized_at,
            )
            for record in records
        ]

    def _transform_one(
        self,
        bronze: Record,
        *,
        generated_at: datetime,
        normalized_at: datetime,
    ) -> Record:
        payload = self._json_object(bronze.get("payload"), "payload")
        business_date = self._required_date(
            bronze.get("business_date"),
            "business_date",
        )
        source_ingestion_run_id = self._required_string(
            bronze.get("source_ingestion_run_id"),
            "source_ingestion_run_id",
        )

        focus = self._transformer.transform(
            payload,
            business_date=business_date,
            ingestion_run_id=source_ingestion_run_id,
            generated_at=generated_at,
            billing_account_name=self._optional_string(
                bronze.get("reference_billing_account_name")
            ),
            billing_account_name_source=self._optional_string(
                bronze.get("reference_billing_account_name_source")
            ),
            invoice_issuer_name=self._optional_string(
                bronze.get("reference_invoice_issuer_name")
            ),
            invoice_issuer_source=self._optional_string(
                bronze.get("reference_invoice_issuer_source")
            ),
        )

        result: dict[str, object] = dict(focus)
        for field in self._DB_DATETIME_FIELDS:
            result[field] = self._naive_utc_datetime(result.get(field), field)

        result.update(
            {
                "x_SourceBronzeId": self._required_int(
                    bronze.get("source_bronze_id"),
                    "source_bronze_id",
                ),
                "x_SourcePayloadHash": self._required_string(
                    bronze.get("source_payload_hash"),
                    "source_payload_hash",
                ),
                "x_SourceIngestionRunId": source_ingestion_run_id,
                "x_SourcePageNumber": self._optional_int(
                    bronze.get("source_page_number")
                ),
                "x_SourceRecordNumber": self._optional_int(
                    bronze.get("source_record_number")
                ),
                "x_SourceApiVersion": self._optional_string(
                    bronze.get("source_api_version")
                ),
                "x_NormalizationVersion": self.NORMALIZATION_VERSION,
                "x_NormalizedAt": normalized_at,
                "ingestion_run_id": None,
            }
        )

        return cast(Record, result)

    @staticmethod
    def _json_object(value: object, field: str) -> dict[str, object]:
        if not isinstance(value, str):
            raise TypeError(f"{field} doit être une chaîne JSON.")

        try:
            decoded: object = json.loads(value)
        except json.JSONDecodeError as exc:
            raise ValueError(f"{field} n'est pas un JSON valide.") from exc

        if not isinstance(decoded, dict):
            raise TypeError(f"{field} doit contenir un objet JSON.")

        raw = cast(dict[object, object], decoded)
        result: dict[str, object] = {}
        for key, item in raw.items():
            if not isinstance(key, str):
                raise TypeError(f"Les clés de {field} doivent être des chaînes.")
            result[key] = item
        return result

    @staticmethod
    def _required_date(value: object, field: str) -> date:
        if isinstance(value, datetime):
            return value.date()
        if isinstance(value, date):
            return value
        raise TypeError(f"{field} doit être une date.")

    @staticmethod
    def _optional_string(value: object) -> str | None:
        if value is None:
            return None
        if isinstance(value, str):
            normalized = value.strip()
            return normalized or None
        if isinstance(value, (int, float, Decimal)) and not isinstance(value, bool):
            return str(value)
        raise TypeError(f"Valeur non convertible en chaîne: {type(value).__name__}.")

    @classmethod
    def _required_string(cls, value: object, field: str) -> str:
        result = cls._optional_string(value)
        if result is None:
            raise ValueError(f"{field} est obligatoire.")
        return result

    @staticmethod
    def _optional_int(value: object) -> int | None:
        if value is None:
            return None
        if isinstance(value, bool) or not isinstance(value, int):
            raise TypeError("La valeur doit être un entier ou None.")
        return value

    @classmethod
    def _required_int(cls, value: object, field: str) -> int:
        result = cls._optional_int(value)
        if result is None:
            raise ValueError(f"{field} est obligatoire.")
        return result

    @staticmethod
    def _naive_utc_datetime(value: object, field: str) -> datetime | None:
        if value is None:
            return None
        if not isinstance(value, datetime):
            raise TypeError(f"{field} doit être un datetime ou None.")
        if value.tzinfo is None:
            return value
        return value.astimezone(UTC).replace(tzinfo=None)
