"""Monthly carbon replay, source fidelity and safe materialization (no cloud I/O)."""

from __future__ import annotations

import json
import re
from datetime import date
from decimal import Decimal
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock
from uuid import uuid4

import pytest
from sqlalchemy.exc import IntegrityError

from finops_batches.application.gcp_carbon_jobs import build_gcp_carbon_job
from finops_batches.bootstrap import build_registry
from finops_batches.config import Settings, load_batch_catalog
from finops_batches.domain.models import BatchExecutionContext
from finops_batches.providers.gcp.carbon import (
    CarbonBigQueryClient,
    CarbonTransformer,
    GcpCarbonSettings,
    marker,
    mass,
)

from . import helpers
from .helpers import Store, find_ddl_file

MONTH = date(2026, 1, 1)


def source(**changes):
    return {
        "usage_month": str(MONTH),
        "billing_account_id": "billing-a",
        "project": {"id": "project-a", "number": "123"},
        "service": {"id": "compute", "description": "Compute Engine"},
        "location": {"region": "europe-west1", "location": "europe-west1-b"},
        "carbon_model_version": 5,
        "carbon_footprint_kgCO2e": {
            "scope1": 0.1,
            "scope2": {"location_based": 0.2, "market_based": 0.05},
            "scope3": 0.3,
        },
        "carbon_footprint_total_kgCO2e": {
            "location_based": 0.6,
            "market_based": 0.45,
            "after_offsets": None,
        },
        "carbon_offsets_kgCO2e": None,
        **changes,
    }


@pytest.fixture
def pipeline(store: Store, tmp_path: Path, monkeypatch):
    tables = {}
    ddl = re.sub(r"--[^\n]*", "", find_ddl_file("048_carbon_footprint.sql").read_text())
    for index, statement in enumerate(ddl.split(";")):
        if not statement.strip().startswith("CREATE TABLE"):
            continue
        path = tmp_path / f"carbon_{index}.sql"
        path.write_text(statement)
        with monkeypatch.context() as scoped:
            scoped.setattr(
                helpers, "find_ddl_file", lambda *a, target=path, **kw: target
            )
            table = store.ddl(path.name)
            tables[table.name] = table
    client = MagicMock()
    client.query.return_value.result.return_value.pages = []
    monkeypatch.setenv("GCP_CARBON_BQ_SOURCE", "test-project.carbon.carbon_footprint")
    monkeypatch.setenv("GCP_CARBON_BQ_LOCATION", "EU")
    monkeypatch.setattr(
        "finops_batches.providers.gcp.carbon.Client", MagicMock(return_value=client)
    )
    telemetry = MagicMock()
    monkeypatch.setattr(
        "finops_batches.application.gcp_carbon_jobs.DataTelemetryClient.from_yaml",
        MagicMock(return_value=telemetry),
    )
    settings = Settings(_env_file=None, finops_database_url=store.url)
    jobs = [
        build_gcp_carbon_job(settings, stage) for stage in ("BRONZE", "SILVER", "GOLD")
    ]
    yield tables, jobs, client, telemetry
    for job in jobs:
        job.close()


def records(pipeline, *values):
    pipeline[2].query.return_value.result.return_value.pages = [
        [{"payload": json.dumps(value)} for value in values]
    ]


def context(day=MONTH):
    return BatchExecutionContext("MANUAL", day, 1, uuid4())


def run(pipeline, index, day=MONTH):
    return pipeline[1][index].run(context(day))


def test_pipeline_preserves_both_bases_and_replaces_revised_month(store, pipeline):
    tables, _jobs, client, telemetry = pipeline
    records(
        pipeline,
        source(),
        source(service={"id": "storage", "description": "Storage"}, project=None),
    )
    assert [run(pipeline, index) for index in range(3)] == [2, 2, 2]
    gold = store.rows(tables["finops_carbon_gold"])
    assert len(gold) == 2 and {row["resource_scope_id"] for row in gold} == {
        "",
        "project-a",
    }
    assert {row["total_market_kg"] for row in gold} == {Decimal("0.45")}
    assert {row["total_location_kg"] for row in gold} == {Decimal("0.6")}
    assert all("carbon_offsets_kgCO2e" not in row for row in gold)
    raw = store.rows(tables["gcp_carbon_bronze"])
    assert json.loads(raw[0]["payload"])["carbon_offsets_kgCO2e"] is None
    # Future Azure adapter's rows are never deleted by GCP materialization.
    with store.engine.begin() as conn:
        conn.execute(
            tables["finops_carbon_gold"].insert(), dict(gold[0]) | {"provider": "AZURE"}
        )
    assert [run(pipeline, index) for index in range(3)] == [2, 2, 2]
    records(
        pipeline,
        source(
            carbon_footprint_total_kgCO2e={"location_based": 2, "market_based": 1.5}
        ),
    )
    assert run(pipeline, 0) == 1
    state = store.rows(tables["finops_carbon_month_state"])[0]
    assert state["silver_source_revision"] != state["bronze_revision"]
    with pytest.raises(ValueError, match="SILVER_MISSING_OR_STALE"):
        run(pipeline, 2)
    assert run(pipeline, 1) == 1 and run(pipeline, 2) == 1
    gold = store.rows(tables["finops_carbon_gold"])
    assert len(gold) == 2
    assert next(row for row in gold if row["provider"] == "GCP")[
        "total_location_kg"
    ] == Decimal(2)
    assert next(row for row in gold if row["provider"] == "AZURE")[
        "total_location_kg"
    ] == Decimal("0.6")
    options = client.query.call_args.kwargs["job_config"]
    assert {item.name: item.value for item in options.query_parameters} == {
        "month_start": MONTH,
        "month_end": date(2026, 2, 1),
    }
    assert client.query.call_args.kwargs["location"] == "EU"
    assert telemetry.start_run.call_count >= 9


def test_empty_requires_explicit_policy_and_does_not_invent_zero_for_absent_import(
    store, pipeline
):
    tables, jobs, _, _ = pipeline
    records(pipeline, source())
    [run(pipeline, i) for i in range(3)]
    old = store.rows(tables["finops_carbon_gold"])
    state = store.rows(tables["finops_carbon_month_state"])
    records(pipeline)
    with pytest.raises(ValueError, match="EMPTY_MONTH"):
        run(pipeline, 0)
    assert store.rows(tables["finops_carbon_gold"]) == old
    assert store.rows(tables["finops_carbon_month_state"]) == state
    jobs[0].extractor.client.config.gcp_carbon_allow_empty_month = True
    assert [run(pipeline, i) for i in range(3)] == [0, 0, 0]
    assert not store.rows(tables["finops_carbon_gold"])
    state = store.rows(tables["finops_carbon_month_state"])[0]
    assert (
        state["gold_source_revision"] == state["silver_revision"]
        and state["gold_source_revision"] > 0
    )
    with pytest.raises(ValueError, match="BRONZE_MISSING"):
        run(pipeline, 1, date(2026, 2, 1))


def test_pagination_failure_keeps_last_month_and_caps_query_cost(store, pipeline):
    tables, jobs, client, _ = pipeline
    records(pipeline, source())
    [run(pipeline, i) for i in range(3)]
    before = store.rows(tables["gcp_carbon_bronze"])

    def pages():
        yield [{"payload": json.dumps(source())}]
        raise ValueError("network interruption")

    client.query.return_value.result.return_value = SimpleNamespace(pages=pages())
    with pytest.raises(ValueError, match="interruption"):
        run(pipeline, 0)
    assert store.rows(tables["gcp_carbon_bronze"]) == before
    client.query.return_value.result.return_value = SimpleNamespace(
        pages=[[{"payload": json.dumps(source())}], [{"payload": json.dumps(source())}]]
    )
    jobs[0].extractor.client.config.gcp_carbon_max_pages = 1
    jobs[0].extractor.client.config.gcp_carbon_maximum_bytes_billed = 12345
    with pytest.raises(ValueError, match="MAX_PAGES"):
        run(pipeline, 0)
    assert client.query.call_args.kwargs["job_config"].maximum_bytes_billed == 12345
    assert store.rows(tables["gcp_carbon_bronze"]) == before


def test_invalid_models_duplicates_and_wrong_month_leave_previous_silver(
    store, pipeline
):
    tables, _, _, _ = pipeline
    records(pipeline, source())
    [run(pipeline, i) for i in range(3)]
    old = store.rows(tables["gcp_carbon_silver"])
    for values, message in [
        ([source(), source()], "DUPLICATE_GRAIN"),
        (
            [source(), source(carbon_model_version=6, service={"id": "other"})],
            "MIXED_MODELS",
        ),
        ([source(usage_month="2026-02-01")], "MONTH_MISMATCH"),
    ]:
        records(pipeline, *values)
        run(pipeline, 0)
        with pytest.raises(ValueError, match=message):
            run(pipeline, 1)
        assert store.rows(tables["gcp_carbon_silver"]) == old


def test_source_revision_and_sql_rollback_protect_month(store, pipeline):
    tables, jobs, _, _ = pipeline
    records(pipeline, source())
    [run(pipeline, i) for i in range(3)]
    ctx = context()
    extracted = jobs[1].extractor.extract(ctx)
    normalized = jobs[1].transformer.transform(extracted)
    jobs[1]._apply_execution_metadata(normalized, context=ctx)
    run(pipeline, 0)
    with pytest.raises(ValueError, match="SOURCE_STALE"):
        jobs[1].loader.load(normalized)
    ctx = context()
    normalized = jobs[1].transformer.transform(jobs[1].extractor.extract(ctx))
    jobs[1]._apply_execution_metadata(normalized, context=ctx)
    normalized.append(dict(normalized[1]))
    old = store.rows(tables["gcp_carbon_silver"])
    state = store.rows(tables["finops_carbon_month_state"])
    with pytest.raises(IntegrityError):
        jobs[1].loader.load(normalized)
    assert store.rows(tables["gcp_carbon_silver"]) == old
    assert store.rows(tables["finops_carbon_month_state"]) == state


def test_month_boundary_other_months_and_registry(store, pipeline, monkeypatch):
    tables, _, _, _ = pipeline
    records(pipeline, source())
    [run(pipeline, i) for i in range(3)]
    records(pipeline, source(usage_month="2026-02-01"))
    assert [run(pipeline, i, date(2026, 2, 1)) for i in range(3)] == [1, 1, 1]
    assert len(store.rows(tables["finops_carbon_gold"])) == 2
    with pytest.raises(ValueError, match="MONTH_REQUIRED"):
        run(pipeline, 0, date(2026, 1, 2))
    with pytest.raises(ValueError, match="COMPLETED_MONTH"):
        run(pipeline, 0, date(2099, 1, 1))
    monkeypatch.setenv("GCP_BILLING_BQ_SOURCE", "test-project.billing.source")
    for stage in ("bronze", "silver", "gold"):
        key = f"gcp.carbon.{stage}.monthly"
        assert key in build_registry(Settings(_env_file=None)).list_keys()
        assert not load_batch_catalog("config/batches.yaml").batches[key].enabled


def test_source_identifier_and_nullable_precision():
    for source_id in (
        "x.y.z;DROP",
        "project.dataset.*",
        "project.dataset.table`",
        "bad",
    ):
        with pytest.raises(ValueError, match="BQ_SOURCE"):
            CarbonBigQueryClient(
                GcpCarbonSettings(gcp_carbon_bq_source=source_id), MagicMock()
            )
    assert mass(None) is None
    assert mass("0.000000000001") == Decimal("0.000000000001")
    assert mass("9007199254740993.123456789012") == Decimal(
        "9007199254740993.123456789012"
    )
    assert mass("99999999999999999999999999.999999999999") == Decimal(
        "99999999999999999999999999.999999999999"
    )
    for value in (
        "NaN",
        "Infinity",
        "1e26",
        "invalid",
        "99999999999999999999999999.9999999999999",
    ):
        with pytest.raises(ValueError):
            mass(value)
    head = marker("SILVER", MONTH)
    result = CarbonTransformer().transform(
        [
            head,
            {
                "payload": json.dumps(
                    source(
                        carbon_footprint_kgCO2e={
                            "scope1": None,
                            "scope2": {"location_based": 0},
                            "scope3": 0,
                        },
                        carbon_footprint_total_kgCO2e={
                            "location_based": 0,
                            "market_based": None,
                        },
                    )
                ),
                "source_hash": "a",
            },
        ]
    )
    assert result[1]["scope1_kg"] is None and result[1][
        "scope2_location_kg"
    ] == Decimal(0)
    assert result[1]["total_market_kg"] is None
