from __future__ import annotations

import hashlib
import json
from collections.abc import Sequence
from datetime import UTC, date, datetime
from typing import cast

from finops_batches.domain.models import Record


class GcpRawJsonBronzeTransformer:
    """Build the same RAW technical envelope used by the Azure pipeline."""

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

    @classmethod
    def _transform_one(cls, record: Record, ingestion_time: datetime) -> Record:
        payload = cls._required_json_object_string(record.get("payload"), "payload")
        payload_object = cls._decode_json_object(payload, "payload")
        request_context = cls._optional_json_value(record.get("request_context"))
        business_date = cls._required_date(record.get("business_date"))

        canonical_payload = cls._canonical_json(payload_object)
        schema_material = cls._schema_shape(payload_object)
        schema_json = cls._canonical_json(schema_material)

        return cast(
            Record,
            {
                "provider_code": cls._required_string(
                    record.get("provider_code"),
                    "provider_code",
                ),
                "source_system": cls._required_string(
                    record.get("source_system"),
                    "source_system",
                ),
                "source_name": cls._required_string(
                    record.get("source_name"),
                    "source_name",
                ),
                "scope_type": cls._optional_string(record.get("scope_type")),
                "scope_id": cls._optional_string(record.get("scope_id")),
                "business_date": business_date,
                "source_uri_logical": cls._optional_string(
                    record.get("source_uri_logical")
                ),
                "request_url": cls._optional_string(record.get("request_url")),
                "page_number": cls._optional_int(record.get("page_number")),
                "source_record_number": cls._optional_int(
                    record.get("source_record_number")
                ),
                "api_version": cls._optional_string(record.get("api_version")),
                "request_context": cls._serialize_optional(request_context),
                "source_hash": cls._sha256(canonical_payload),
                "schema_hash": cls._sha256(schema_json),
                "ingestion_run_id": None,
                "ingestion_time": ingestion_time,
                "payload": payload,
            },
        )

    @classmethod
    def _required_json_object_string(cls, value: object, field: str) -> str:
        if not isinstance(value, str) or not value.strip():
            raise TypeError(f"{field} doit être une chaîne JSON non vide.")
        cls._decode_json_object(value, field)
        return value.strip()

    @staticmethod
    def _decode_json_object(value: str, field: str) -> dict[str, object]:
        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

    @classmethod
    def _optional_json_value(cls, value: object) -> object | None:
        if value is None:
            return None

        if isinstance(value, dict):
            raw_mapping = cast(dict[object, object], value)
            result: dict[str, object] = {}

            for key, item in raw_mapping.items():
                if not isinstance(key, str):
                    raise TypeError(
                        "Les clés de request_context doivent être des chaînes."
                    )

                result[key] = cls._optional_json_value(item)

            return result

        if isinstance(value, list):
            raw_list = cast(list[object], value)

            return [cls._optional_json_value(item) for item in raw_list]

        if isinstance(value, (str, int, float, bool)):
            return value

        raise TypeError("request_context doit être une valeur JSON compatible ou None.")

    @staticmethod
    def _schema_shape(value: object) -> object:
        if isinstance(value, dict):
            raw = cast(dict[object, object], value)
            shape: dict[str, object] = {}
            for key, item in raw.items():
                if not isinstance(key, str):
                    raise TypeError("Les clés du payload doivent être des chaînes.")
                shape[key] = GcpRawJsonBronzeTransformer._schema_shape(item)
            return shape
        if isinstance(value, list):
            return "array"
        if value is None:
            return "null"
        if isinstance(value, bool):
            return "boolean"
        if isinstance(value, (int, float)):
            return "number"
        if isinstance(value, str):
            return "string"
        raise TypeError(f"Type JSON non supporté: {type(value).__name__}.")

    @staticmethod
    def _canonical_json(value: object) -> str:
        return json.dumps(
            value,
            sort_keys=True,
            ensure_ascii=False,
            separators=(",", ":"),
        )

    @classmethod
    def _serialize_optional(cls, value: object | None) -> str | None:
        if value is None:
            return None
        return cls._canonical_json(value)

    @staticmethod
    def _sha256(value: str) -> str:
        return hashlib.sha256(value.encode("utf-8")).hexdigest()

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

    @staticmethod
    def _optional_string(value: object) -> str | None:
        if value is None:
            return None
        if not isinstance(value, str):
            raise TypeError("La valeur doit être une chaîne ou None.")
        normalized = value.strip()
        return normalized or None

    @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

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