"""Monthly Carbon Footprint export: preserve source estimates and both bases."""

from __future__ import annotations

import hashlib
import json
import re
from collections.abc import Iterator, Mapping, Sequence
from datetime import UTC, date, datetime
from decimal import Decimal, InvalidOperation, localcontext
from typing import cast

from google.cloud.bigquery import Client, QueryJobConfig, ScalarQueryParameter
from pydantic import Field
from sqlalchemy import MetaData, Table, create_engine, select

from finops_batches.config import BaseApplicationSettings
from finops_batches.domain.models import BatchExecutionContext, Record
from finops_batches.providers.gcp.billing_client import BigQueryClientProtocol

MARKER = "_carbon_month"
METRICS = (
    "scope1_kg",
    "scope2_location_kg",
    "scope2_market_kg",
    "scope3_kg",
    "total_location_kg",
    "total_market_kg",
)


class GcpCarbonSettings(BaseApplicationSettings):
    gcp_carbon_bq_source: str = Field(
        default="", validation_alias="GCP_CARBON_BQ_SOURCE"
    )
    gcp_carbon_bq_project_id: str = Field(
        default="", validation_alias="GCP_CARBON_BQ_PROJECT_ID"
    )
    gcp_carbon_bq_location: str = Field(
        default="EU", min_length=1, validation_alias="GCP_CARBON_BQ_LOCATION"
    )
    gcp_carbon_page_size: int = Field(
        default=1000, ge=1, le=100000, validation_alias="GCP_CARBON_PAGE_SIZE"
    )
    gcp_carbon_max_pages: int = Field(
        default=10000, ge=1, validation_alias="GCP_CARBON_MAX_PAGES"
    )
    gcp_carbon_query_timeout: float = Field(
        default=300, gt=0, validation_alias="GCP_CARBON_QUERY_TIMEOUT_SECONDS"
    )
    gcp_carbon_maximum_bytes_billed: int = Field(
        default=0, ge=0, validation_alias="GCP_CARBON_MAXIMUM_BYTES_BILLED"
    )
    gcp_carbon_allow_empty_month: bool = Field(
        default=False, validation_alias="GCP_CARBON_ALLOW_EMPTY_MONTH"
    )


def month(value: date) -> date:
    if isinstance(value, datetime) or value.day != 1:
        raise ValueError(
            "CARBON_MONTH_REQUIRED: business_date must be the first day of a month"
        )
    return value


def next_month(value: date) -> date:
    return date(value.year + (value.month == 12), value.month % 12 + 1, 1)


def marker(stage: str, day: date, **extra: object) -> Record:
    return {
        MARKER: stage,
        "business_date": month(day),
        "ingestion_run_id": None,
        **extra,
    }


class CarbonBigQueryClient:
    def __init__(
        self, config: GcpCarbonSettings, client: BigQueryClientProtocol | None = None
    ):
        self.config = config
        source = config.gcp_carbon_bq_source.strip()
        if not re.fullmatch(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_]+\.[A-Za-z0-9_]+", source):
            raise ValueError(
                "GCP_CARBON_BQ_SOURCE must be project.dataset.table_or_view without wildcard"
            )
        self.source = source
        self.client = client or cast(
            BigQueryClientProtocol,
            Client(
                project=config.gcp_carbon_bq_project_id or None,
                location=config.gcp_carbon_bq_location,
            ),
        )

    def rows(self, day: date) -> Iterator[str]:
        month(day)
        options = QueryJobConfig(
            use_legacy_sql=False,
            query_parameters=[
                ScalarQueryParameter("month_start", "DATE", day),
                ScalarQueryParameter("month_end", "DATE", next_month(day)),
            ],
        )
        if self.config.gcp_carbon_maximum_bytes_billed:
            options.maximum_bytes_billed = self.config.gcp_carbon_maximum_bytes_billed
        query = f"SELECT TO_JSON_STRING(src) AS payload FROM `{self.source}` src WHERE usage_month>=@month_start AND usage_month<@month_end ORDER BY TO_HEX(SHA256(TO_JSON_STRING(src)))"
        job = self.client.query(
            query, job_config=options, location=self.config.gcp_carbon_bq_location
        )
        for number, page in enumerate(
            job.result(
                timeout=self.config.gcp_carbon_query_timeout,
                page_size=self.config.gcp_carbon_page_size,
            ).pages,
            1,
        ):
            if number > self.config.gcp_carbon_max_pages:
                raise ValueError("GCP_CARBON_MAX_PAGES_EXCEEDED")
            for row in page:
                payload = row["payload"]
                if not isinstance(payload, str):
                    raise TypeError("CARBON_PAYLOAD_MUST_BE_JSON_STRING")
                yield payload

    def close(self) -> None:
        self.client.close()


class CarbonBronzeExtractor:
    def __init__(self, client: CarbonBigQueryClient):
        self.client = client

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        day = month(context.business_date)
        if day >= datetime.now(UTC).date().replace(day=1):
            raise ValueError("CARBON_COMPLETED_MONTH_REQUIRED")
        rows = list(self.client.rows(day))
        if not rows and not self.client.config.gcp_carbon_allow_empty_month:
            raise ValueError(
                "CARBON_EMPTY_MONTH: no confirmed export; previous snapshot retained"
            )
        now = datetime.now(UTC).replace(tzinfo=None)
        result: list[Record] = [marker("BRONZE", day, source_table=self.client.source)]
        for i, payload in enumerate(rows, 1):
            result.append(
                {
                    "business_date": day,
                    "record_number": i,
                    "payload": payload,
                    "source_hash": hashlib.sha256(payload.encode()).hexdigest(),
                    "ingestion_run_id": None,
                    "ingested_at": now,
                }
            )
        return result

    def close(self) -> None:
        self.client.close()


class CarbonLocalExtractor:
    def __init__(self, *, database_url: str, stage: str, provider: str = "GCP"):
        if provider not in {"GCP", "AZURE"}:
            raise ValueError("CARBON_INVALID_PROVIDER")
        self.provider = provider
        if stage not in {"SILVER", "GOLD"}:
            raise ValueError("CARBON_INVALID_STAGE")
        self.stage = stage
        self.engine = create_engine(database_url, pool_pre_ping=True)
        try:
            metadata = MetaData()
            self.source = Table(
                f"{provider.lower()}_carbon_bronze"
                if stage == "SILVER"
                else f"{provider.lower()}_carbon_silver",
                metadata,
                autoload_with=self.engine,
            )
            self.state = Table(
                "finops_carbon_month_state", metadata, autoload_with=self.engine
            )
        except Exception:
            self.engine.dispose()
            raise

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        day = month(context.business_date)
        with self.engine.connect() as connection:
            state = (
                connection.execute(
                    select(self.state).where(
                        self.state.c.provider == self.provider,
                        self.state.c.business_date == day,
                    )
                )
                .mappings()
                .one_or_none()
            )
            if state is None or state["bronze_revision"] == 0:
                raise ValueError("CARBON_BRONZE_MISSING")
            if self.stage == "GOLD" and (
                state["silver_revision"] == 0
                or state["silver_source_revision"] != state["bronze_revision"]
            ):
                raise ValueError("CARBON_SILVER_MISSING_OR_STALE")
            rows = (
                connection.execute(
                    select(self.source).where(self.source.c.business_date == day)
                )
                .mappings()
                .all()
            )
            if (
                len(rows)
                != state["bronze_rows" if self.stage == "SILVER" else "silver_rows"]
            ):
                raise ValueError("CARBON_SOURCE_COUNT_MISMATCH")
            return [
                marker(
                    self.stage,
                    day,
                    source_revision=state[
                        "bronze_revision"
                        if self.stage == "SILVER"
                        else "silver_revision"
                    ],
                ),
                *(dict(row) for row in rows),
            ]

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


def text(value: object, size: int) -> str:
    if value is None:
        return ""
    if not isinstance(value, str):
        raise TypeError("CARBON_INVALID_DIMENSION")
    if len(value) > size:
        raise ValueError("CARBON_DIMENSION_TOO_LONG")
    return value


def mass(value: object) -> Decimal | None:
    if value is None:
        return None
    if isinstance(value, bool) or not isinstance(value, (Decimal, int, str)):
        raise TypeError("CARBON_INVALID_MASS")
    try:
        amount = Decimal(value)
    except InvalidOperation as error:
        raise ValueError("CARBON_INVALID_MASS") from error
    if not amount.is_finite() or amount.copy_abs() >= Decimal("1e26"):
        raise ValueError("CARBON_MASS_OUT_OF_RANGE")
    with localcontext() as precision:
        precision.prec = 60
        rounded = amount.quantize(Decimal("0.000000000001"))
        if rounded.copy_abs() >= Decimal("1e26"):
            raise ValueError("CARBON_MASS_OUT_OF_RANGE")
        return rounded


def object_at(source: Mapping[str, object], key: str) -> Mapping[str, object]:
    value = source.get(key)
    if value is None:
        return {}
    if not isinstance(value, dict):
        raise TypeError("CARBON_INVALID_OBJECT")
    return value


class CarbonTransformer:
    def transform(self, records: Sequence[Record]) -> list[Record]:
        if not records or records[0].get(MARKER) not in {"BRONZE", "SILVER", "GOLD"}:
            raise ValueError("CARBON_MONTH_MARKER_REQUIRED")
        head = dict(records[0])
        stage = head[MARKER]
        if stage == "BRONZE":
            return [dict(row) for row in records]
        result = [head]
        seen: set[str] = set()
        versions: dict[str, str] = {}
        for raw in records[1:]:
            if stage == "GOLD":
                row = dict(raw)
                row.pop("source_hash")
                row["provider"] = "GCP"
                row["ingestion_run_id"] = None
            else:
                value = raw.get("payload")
                if not isinstance(value, str):
                    raise TypeError("CARBON_PAYLOAD_REQUIRED")
                source = json.loads(value, parse_float=Decimal)
                if not isinstance(source, dict):
                    raise TypeError("CARBON_PAYLOAD_OBJECT_REQUIRED")
                if source.get("usage_month") != str(head["business_date"]):
                    raise ValueError("CARBON_SOURCE_MONTH_MISMATCH")
                project, service, location = (
                    object_at(source, name)
                    for name in ("project", "service", "location")
                )
                account = text(source.get("billing_account_id"), 128)
                if not account.strip():
                    raise ValueError("CARBON_ACCOUNT_REQUIRED")
                version = source.get("carbon_model_version")
                if (
                    isinstance(version, bool)
                    or not isinstance(version, int)
                    or version < 0
                ):
                    raise ValueError("CARBON_MODEL_VERSION_REQUIRED")
                dimensions = {
                    "billing_account_id": account,
                    "resource_scope_id": text(project.get("id"), 255),
                    "resource_scope_number": text(project.get("number"), 64),
                    "service_id": text(service.get("id"), 128),
                    "region": text(location.get("region"), 128),
                    "location": text(location.get("location"), 128),
                }
                key = hashlib.sha256(
                    json.dumps(
                        dimensions,
                        sort_keys=True,
                        ensure_ascii=False,
                        separators=(",", ":"),
                    ).encode()
                ).hexdigest()
                if account in versions and versions[account] != str(version):
                    raise ValueError(
                        "CARBON_MIXED_MODELS: provide a view with one model per account/month"
                    )
                versions[account] = str(version)
                footprint = object_at(source, "carbon_footprint_kgCO2e")
                scope2 = object_at(footprint, "scope2")
                total = object_at(source, "carbon_footprint_total_kgCO2e")
                row = {
                    "business_date": head["business_date"],
                    "grain_hash": key,
                    **dimensions,
                    "service_name": text(service.get("description"), 500),
                    "model_version": str(version),
                    "scope1_kg": mass(footprint.get("scope1")),
                    "scope2_location_kg": mass(scope2.get("location_based")),
                    "scope2_market_kg": mass(scope2.get("market_based")),
                    "scope3_kg": mass(footprint.get("scope3")),
                    "total_location_kg": mass(total.get("location_based")),
                    "total_market_kg": mass(total.get("market_based")),
                    "source_hash": raw["source_hash"],
                    "ingestion_run_id": None,
                }
            key = str(row["grain_hash"])
            if key in seen:
                raise ValueError(
                    "CARBON_DUPLICATE_GRAIN: source rows must not be counted twice"
                )
            seen.add(key)
            result.append(row)
        return result
