from __future__ import annotations

from collections.abc import Sequence
from datetime import date, datetime

from sqlalchemy import MetaData, Table, and_, create_engine, func, select, update
from sqlalchemy.engine import Connection, Engine, RowMapping

from finops_batches.domain.models import Record


class TagDiscoveryLoader:
    """Upsert discovered tag keys and values without overwriting governance.

    The loader deliberately never overwrites administrative fields such as:

    - tag_tracking.status
    - tag_tracking.enabled
    - tag_tracking.canonical_tag_name
    - tag_tracking.column_name
    - tag_value_mapping.status
    - tag_value_mapping.canonical_value
    - descriptions and display order

    ``first_seen_date`` / ``last_seen_date`` represent FOCUS business dates,
    i.e. acquisition/reporting dates. Optional ``first_usage_date`` /
    ``last_usage_date`` columns are maintained when they exist in the target
    tables.

    occurrence/resource counters emitted by the extractor are intentionally
    not accumulated in the master tables. Without a daily observation table,
    cumulative counters cannot remain correct under replay and late-arriving
    data. Existing counter columns therefore keep their database defaults.
    """

    def __init__(
        self,
        *,
        database_url: str,
        tag_tracking_table: str = "tag_tracking",
        tag_value_mapping_table: str = "tag_value_mapping",
    ) -> None:
        self._engine: Engine = create_engine(
            database_url,
            pool_pre_ping=True,
        )

        metadata = MetaData()
        self._tag_tracking = Table(
            tag_tracking_table,
            metadata,
            autoload_with=self._engine,
        )
        self._tag_value_mapping = Table(
            tag_value_mapping_table,
            metadata,
            autoload_with=self._engine,
        )

        self._validate_schema()

    def load(self, records: Sequence[Record]) -> int:
        if not records:
            return 0

        key_records = [
            record for record in records if record.get("record_type") == "TAG_KEY"
        ]
        value_records = [
            record for record in records if record.get("record_type") == "TAG_VALUE"
        ]

        processed = 0

        with self._engine.begin() as connection:
            for record in key_records:
                self._upsert_key(connection, record)
                processed += 1

            tag_references = self._load_tag_references(
                connection,
                key_records,
            )

            for record in value_records:
                if self._upsert_value(
                    connection,
                    record,
                    tag_references,
                ):
                    processed += 1

        return processed

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

    def _upsert_key(
        self,
        connection: Connection,
        record: Record,
    ) -> None:
        table = self._tag_tracking

        provider = self._required_string(record.get("provider"), "provider")
        scope = self._required_string(record.get("scope"), "scope")
        source_tag_key = self._required_string(
            record.get("source_tag_key"),
            "source_tag_key",
        )
        business_date = self._required_date(
            record.get("business_date"),
            "business_date",
        )

        existing = (
            connection.execute(
                select(table).where(
                    and_(
                        func.lower(table.c.provider) == provider.casefold(),
                        func.lower(table.c.scope) == scope.casefold(),
                        func.lower(table.c.source_tag_key) == source_tag_key.casefold(),
                    )
                )
            )
            .mappings()
            .first()
        )

        if existing is None:
            values: dict[str, object] = {
                "provider": provider,
                "scope": scope,
                "source_tag_key": source_tag_key,
                "status": "DISCOVERED",
                "first_seen_date": business_date,
                "last_seen_date": business_date,
            }

            if "enabled" in table.c:
                values["enabled"] = False

            self._apply_optional_usage_dates(
                values,
                record=record,
                table=table,
            )

            connection.execute(table.insert().values(**values))
            return

        updates = self._build_observation_updates(
            existing=existing,
            record=record,
            table=table,
            business_date=business_date,
        )

        if updates:
            connection.execute(
                update(table).where(table.c.id == existing["id"]).values(**updates)
            )

    def _load_tag_references(
        self,
        connection: Connection,
        records: Sequence[Record],
    ) -> dict[tuple[str, str, str], tuple[int, str]]:
        if not records:
            return {}

        requested: set[tuple[str, str, str]] = set()

        for record in records:
            provider = self._required_string(record.get("provider"), "provider")
            scope = self._required_string(record.get("scope"), "scope")
            source_tag_key = self._required_string(
                record.get("source_tag_key"),
                "source_tag_key",
            )
            requested.add(
                (
                    provider.casefold(),
                    scope.casefold(),
                    source_tag_key.casefold(),
                )
            )

        table = self._tag_tracking
        statement = select(
            table.c.id,
            table.c.provider,
            table.c.scope,
            table.c.source_tag_key,
            table.c.status,
        )

        references: dict[tuple[str, str, str], tuple[int, str]] = {}

        for row in connection.execute(statement).mappings():
            provider = self._required_string(row["provider"], "provider")
            scope = self._required_string(row["scope"], "scope")
            source_tag_key = self._required_string(
                row["source_tag_key"],
                "source_tag_key",
            )

            identity = (
                provider.casefold(),
                scope.casefold(),
                source_tag_key.casefold(),
            )

            if identity not in requested:
                continue

            tag_id = self._required_int(row["id"], "tag_tracking.id")
            status = self._required_string(row["status"], "status")
            references[identity] = (tag_id, status)

        return references

    def _upsert_value(
        self,
        connection: Connection,
        record: Record,
        tag_references: dict[tuple[str, str, str], tuple[int, str]],
    ) -> bool:
        provider = self._required_string(record.get("provider"), "provider")
        scope = self._required_string(record.get("scope"), "scope")
        source_tag_key = self._required_string(
            record.get("source_tag_key"),
            "source_tag_key",
        )

        identity = (
            provider.casefold(),
            scope.casefold(),
            source_tag_key.casefold(),
        )
        tag_reference = tag_references.get(identity)

        if tag_reference is None:
            raise ValueError(
                "TAG_TRACKING_NOT_FOUND_AFTER_UPSERT: "
                f"{provider}/{scope}/{source_tag_key}"
            )

        tag_tracking_id, tag_status = tag_reference
        if tag_status == "IGNORED":
            return False

        table = self._tag_value_mapping
        source_value = self._required_string(
            record.get("source_value"),
            "source_value",
        )
        normalized_source_value = self._required_string(
            record.get("normalized_source_value"),
            "normalized_source_value",
        )
        business_date = self._required_date(
            record.get("business_date"),
            "business_date",
        )

        existing = (
            connection.execute(
                select(table).where(
                    and_(
                        table.c.tag_tracking_id == tag_tracking_id,
                        table.c.normalized_source_value == normalized_source_value,
                    )
                )
            )
            .mappings()
            .first()
        )

        if existing is None:
            values: dict[str, object] = {
                "tag_tracking_id": tag_tracking_id,
                "source_value": source_value,
                "normalized_source_value": normalized_source_value,
                "status": "DISCOVERED",
                "first_seen_date": business_date,
                "last_seen_date": business_date,
            }

            self._apply_optional_usage_dates(
                values,
                record=record,
                table=table,
            )

            connection.execute(table.insert().values(**values))
            return True

        updates = self._build_observation_updates(
            existing=existing,
            record=record,
            table=table,
            business_date=business_date,
        )

        if updates:
            connection.execute(
                update(table).where(table.c.id == existing["id"]).values(**updates)
            )

        return True

    def _build_observation_updates(
        self,
        *,
        existing: RowMapping,
        record: Record,
        table: Table,
        business_date: date,
    ) -> dict[str, object]:
        updates: dict[str, object] = {}

        existing_first_seen = self._optional_date(existing["first_seen_date"])
        existing_last_seen = self._optional_date(existing["last_seen_date"])

        if existing_first_seen is None or business_date < existing_first_seen:
            updates["first_seen_date"] = business_date

        if existing_last_seen is None or business_date > existing_last_seen:
            updates["last_seen_date"] = business_date

        if "first_usage_date" in table.c:
            incoming_first_usage = self._optional_date(record.get("first_usage_date"))
            existing_first_usage = self._optional_date(existing.get("first_usage_date"))

            if incoming_first_usage is not None and (
                existing_first_usage is None
                or incoming_first_usage < existing_first_usage
            ):
                updates["first_usage_date"] = incoming_first_usage

        if "last_usage_date" in table.c:
            incoming_last_usage = self._optional_date(record.get("last_usage_date"))
            existing_last_usage = self._optional_date(existing.get("last_usage_date"))

            if incoming_last_usage is not None and (
                existing_last_usage is None or incoming_last_usage > existing_last_usage
            ):
                updates["last_usage_date"] = incoming_last_usage

        return updates

    def _apply_optional_usage_dates(
        self,
        values: dict[str, object],
        *,
        record: Record,
        table: Table,
    ) -> None:
        if "first_usage_date" in table.c:
            first_usage_date = self._optional_date(record.get("first_usage_date"))
            values["first_usage_date"] = first_usage_date

        if "last_usage_date" in table.c:
            last_usage_date = self._optional_date(record.get("last_usage_date"))
            values["last_usage_date"] = last_usage_date

    def _validate_schema(self) -> None:
        required_tracking = {
            "id",
            "provider",
            "scope",
            "source_tag_key",
            "status",
            "first_seen_date",
            "last_seen_date",
        }
        required_values = {
            "id",
            "tag_tracking_id",
            "source_value",
            "normalized_source_value",
            "canonical_value",
            "status",
            "first_seen_date",
            "last_seen_date",
        }

        missing_tracking = sorted(
            required_tracking.difference(self._tag_tracking.c.keys())
        )
        if missing_tracking:
            raise ValueError(
                "Colonnes absentes de tag_tracking: " + ", ".join(missing_tracking)
            )

        missing_values = sorted(
            required_values.difference(self._tag_value_mapping.c.keys())
        )
        if missing_values:
            raise ValueError(
                "Colonnes absentes de tag_value_mapping: " + ", ".join(missing_values)
            )

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

        normalized = value.strip()
        if not normalized:
            raise ValueError(f"{field} ne peut pas être vide.")

        return normalized

    @staticmethod
    def _required_int(value: object, field: str) -> int:
        if isinstance(value, bool) or not isinstance(value, int):
            raise TypeError(f"{field} doit être un entier.")
        return value

    @staticmethod
    def _required_date(value: object, field: str) -> date:
        parsed = TagDiscoveryLoader._optional_date(value)
        if parsed is None:
            raise ValueError(f"{field} est obligatoire.")
        return parsed

    @staticmethod
    def _optional_date(value: object) -> date | None:
        if value is None:
            return None

        if isinstance(value, datetime):
            return value.date()

        if isinstance(value, date):
            return value

        if isinstance(value, str):
            normalized = value.strip()
            if not normalized:
                return None

            try:
                return datetime.fromisoformat(normalized).date()
            except ValueError as exc:
                raise ValueError(f"Date invalide: {value!r}.") from exc

        raise TypeError(
            "La valeur de date doit être une date, un datetime ou une chaîne."
        )
