"""Azure API contracts and shared monthly Gold, without cloud or MariaDB I/O."""

from __future__ import annotations

import json
import re
from datetime import date
from decimal import Decimal
from unittest.mock import MagicMock
from uuid import uuid4

import httpx
import pytest
from sqlalchemy.exc import IntegrityError

from finops_batches.application.azure_carbon_jobs import build_azure_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.azure.carbon import (
    API_VERSION,
    AzureCarbonClient,
    AzureCarbonSettings,
)
from finops_batches.providers.gcp.config import GcpBillingSettings

from . import helpers
from .helpers import find_ddl_file

DAY = date(2026, 1, 1)
SUB = "11111111-1111-4111-8111-111111111111"
OTHER = "22222222-2222-4222-8222-222222222222"


def item(name="a", **changes):
    return {
        "dataType": "ResourceItemDetailsData",
        "categoryType": "Resource",
        "subscriptionId": SUB,
        "resourceId": f"/subscriptions/{SUB}/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/{name}",
        "resourceType": "microsoft.compute/virtualmachines",
        "location": "west europe",
        "latestMonthEmissions": "PRECISE",
        **changes,
    }


def response(values, **changes):
    return {
        "subscriptionAccessDecisionList": [
            {"subscriptionId": SUB, "decision": "Allowed"}
        ],
        "value": values,
        **changes,
    }


@pytest.fixture
def pipeline(store, tmp_path, monkeypatch):
    tables = {}
    for filename in ("048_carbon_footprint.sql", "049_azure_carbon.sql"):
        ddl = re.sub(r"--[^\n]*", "", find_ddl_file(filename).read_text())
        for index, statement in enumerate(ddl.split(";")):
            if not statement.strip().startswith("CREATE TABLE"):
                continue
            path = tmp_path / f"{filename}_{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
    state = {"items": [item(), item("b")], "mode": "ok", "calls": []}

    def handler(request):
        body = json.loads(request.content)
        state["calls"].append(body)
        assert request.url.params["api-version"] == API_VERSION
        assert body["dateRange"] == {"start": str(DAY), "end": str(DAY)}
        assert request.headers["Authorization"] == "Bearer fake"
        scope = body["carbonScopeList"]
        amount = (
            {"Scope1": "0.1", "Scope2": "0.2", "Scope3": "0.3"}[scope[0]]
            if len(scope) == 1
            else "0.6"
        )
        data = response(state["items"])
        if state["mode"] == "omit_decisions":
            data.pop("subscriptionAccessDecisionList")
        if state["mode"] == "null_decisions":
            data["subscriptionAccessDecisionList"] = None
        if state["mode"] == "denied":
            data["subscriptionAccessDecisionList"][0]["decision"] = "Denied"
        if state["mode"] == "cycle":
            data["skipToken"] = "same-token"
        if state["mode"] == "failure" and scope == ["Scope3"]:
            return httpx.Response(503)
        if state["mode"] == "missing" and scope == ["Scope2"]:
            data["value"] = state["items"][:1]
        return httpx.Response(200, text=json.dumps(data).replace('"PRECISE"', amount))

    monkeypatch.setenv("AZURE_CARBON_SUBSCRIPTION_IDS", SUB)
    monkeypatch.setenv("AZURE_CARBON_MAX_ATTEMPTS", "1")
    token = MagicMock()
    token.get_token.return_value = "fake"
    monkeypatch.setattr(
        "finops_batches.application.azure_carbon_jobs.AzureArmTokenProvider",
        MagicMock(return_value=token),
    )
    monkeypatch.setattr(
        "finops_batches.application.azure_carbon_jobs.AzureCarbonClient",
        lambda config, token_provider, on_close: AzureCarbonClient(
            config,
            token_provider,
            httpx.Client(transport=httpx.MockTransport(handler)),
            on_close=on_close,
        ),
    )
    monkeypatch.setattr(
        "finops_batches.application.azure_carbon_jobs.DataTelemetryClient.from_yaml",
        MagicMock(),
    )
    settings = Settings(_env_file=None, finops_database_url=store.url)
    # Pass a client explicitly to avoid mocking unrelated HTTP clients.
    jobs = [
        build_azure_carbon_job(settings, stage)
        for stage in ("BRONZE", "SILVER", "GOLD")
    ]
    yield tables, jobs, state, token
    for job in jobs:
        job.close()


def run(pipeline, stage):
    return pipeline[1][stage].run(BatchExecutionContext("MANUAL", DAY, 1, uuid4()))


def test_shared_gold_replay_and_provider_isolation(store, pipeline):
    tables, jobs, state, token = pipeline
    assert [run(pipeline, i) for i in range(3)] == [4, 1, 1]
    gold = store.rows(tables["finops_carbon_gold"])
    row = gold[0]
    assert row["provider"] == "AZURE" and row["resource_scope_id"] == SUB
    assert row["billing_account_id"] == "" and row["model_version"] == ""
    assert row["total_market_kg"] == Decimal("1.2") and row[
        "scope2_market_kg"
    ] == Decimal("0.4")
    assert row["total_location_kg"] is None and row["scope2_location_kg"] is None
    with store.engine.begin() as connection:
        connection.execute(
            tables["finops_carbon_gold"].insert(), dict(row) | {"provider": "GCP"}
        )
    state["items"] = [item()]
    assert run(pipeline, 0) == 4
    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 {r["provider"]: r["total_market_kg"] for r in gold} == {
        "AZURE": Decimal("0.6"),
        "GCP": Decimal("1.2"),
    }
    assert [run(pipeline, i) for i in range(3)] == [4, 1, 1]
    assert len(store.rows(tables["finops_carbon_gold"])) == 2
    jobs[0].close()
    assert token.close.called


@pytest.mark.parametrize(
    "mode,error",
    [
        ("denied", "ACCESS_NOT_CONFIRMED"),
        ("cycle", "INVALID_PAGINATION"),
        ("failure", "HTTP_503"),
    ],
)
def test_partial_acquisition_never_replaces_bronze(store, pipeline, mode, error):
    tables, _, state, _ = pipeline
    run(pipeline, 0)
    before = store.rows(tables["azure_carbon_bronze"])
    state["mode"] = mode
    with pytest.raises(ValueError, match=error):
        run(pipeline, 0)
    assert store.rows(tables["azure_carbon_bronze"]) == before


def test_empty_guard_and_explicit_empty_replacement(store, pipeline, monkeypatch):
    tables, jobs, state, _ = pipeline
    for i in range(3):
        run(pipeline, i)
    state["items"] = []
    with pytest.raises(ValueError, match="EMPTY_MONTH"):
        run(pipeline, 0)
    assert len(store.rows(tables["finops_carbon_gold"])) == 1
    jobs[0].extractor.client.config.azure_carbon_allow_empty_month = True
    assert [run(pipeline, i) for i in range(3)] == [4, 0, 0]
    assert not store.rows(tables["finops_carbon_gold"])
    assert store.rows(tables["finops_carbon_month_state"])[0]["gold_rows"] == 0


def test_missing_scope_stays_unknown_and_duplicate_resource_rolls_back(store, pipeline):
    tables, _, state, _ = pipeline
    state["mode"] = "missing"
    for i in range(3):
        run(pipeline, i)
    row = store.rows(tables["finops_carbon_gold"])[0]
    assert row["scope2_market_kg"] is None and row["total_market_kg"] == Decimal("1.2")
    state["mode"] = "ok"
    state["items"] = [item(), item()]
    run(pipeline, 0)
    before = store.rows(tables["azure_carbon_silver"])
    with pytest.raises(ValueError, match="DUPLICATE_RESOURCE_SCOPE"):
        run(pipeline, 1)
    assert store.rows(tables["azure_carbon_silver"]) == before


def test_stale_extraction_and_failure_after_delete_are_atomic(
    store, pipeline, monkeypatch
):
    tables, jobs, _state, _ = pipeline
    for i in range(3):
        run(pipeline, i)
    old = jobs[1].extractor.extract(BatchExecutionContext("MANUAL", DAY, 1, uuid4()))
    run(pipeline, 0)
    old = jobs[1].transformer.transform(old)
    for row in old:
        row["ingestion_run_id"] = str(uuid4())
    # Use one run id for all records, as DataBatchJob does.
    for row in old:
        row["ingestion_run_id"] = old[0]["ingestion_run_id"]
    with pytest.raises(ValueError, match="SOURCE_STALE"):
        jobs[1].loader.load(old)
    before = store.rows(tables["azure_carbon_silver"])

    def broken(*a, **kw):
        raise IntegrityError("insert", {}, Exception("forced"))

    monkeypatch.setattr(jobs[1].loader.table, "insert", broken)
    with pytest.raises(IntegrityError):
        run(pipeline, 1)
    assert store.rows(tables["azure_carbon_silver"]) == before


def test_subscription_configuration_and_lazy_registry(monkeypatch):
    # The registry also validates GCP Billing settings. Use an explicit fixture
    # rather than relying on a developer's .env (absent from CI).
    monkeypatch.setenv("GCP_BILLING_BQ_SOURCE", "test-project.billing.source")
    monkeypatch.setitem(GcpBillingSettings.model_config, "env_file", None)
    monkeypatch.delenv("AZURE_CARBON_SUBSCRIPTION_IDS", raising=False)
    config = AzureCarbonSettings(_env_file=None)
    assert config.subscriptions(SUB) == [SUB]
    assert AzureCarbonSettings(
        _env_file=None, azure_carbon_subscription_ids=SUB + "," + OTHER
    ).subscriptions("") == [SUB, OTHER]
    for value in ("", "not-a-uuid", SUB + "," + SUB):
        with pytest.raises(ValueError):
            AzureCarbonSettings(
                _env_file=None, azure_carbon_subscription_ids=value
            ).subscriptions("")
    keys = build_registry(Settings(_env_file=None)).list_keys()
    catalog = load_batch_catalog("config/batches.yaml")
    for stage in ("bronze", "silver", "gold"):
        key = f"azure.carbon.{stage}.monthly"
        assert key in keys and not catalog.batches[key].enabled


def test_retry_pagination_payload_and_auth_header(monkeypatch):
    sleeps = []
    monkeypatch.setattr(
        "finops_batches.providers.azure.carbon.time.sleep", sleeps.append
    )
    calls = []

    def handler(request):
        calls.append(json.loads(request.content))
        if len(calls) == 1:
            return httpx.Response(429, headers={"Retry-After": "1000"})
        return httpx.Response(
            200, json=response([], skipToken="next" if len(calls) == 2 else None)
        )

    client = AzureCarbonClient(
        AzureCarbonSettings(_env_file=None),
        lambda: "fake",
        httpx.Client(transport=httpx.MockTransport(handler)),
    )
    try:
        assert len(client.pages(SUB, DAY, "scope1_kg")) == 2
        assert calls[-1]["skipToken"] == "next" and sleeps == [30]
        assert calls[0]["subscriptionList"] == [SUB] and calls[0][
            "carbonScopeList"
        ] == ["Scope1"]
    finally:
        client.close()


@pytest.mark.parametrize(
    "changes,error",
    [
        ({"subscriptionId": OTHER}, "RESOURCE_SCOPE_MISMATCH"),
        ({"resourceId": "/unexpected"}, "RESOURCE_SCOPE_MISMATCH"),
        ({"dataType": "ItemDetailsData"}, "INVALID_RESOURCE"),
        ({"latestMonthEmissions": "NaN"}, "MASS_OUT_OF_RANGE"),
    ],
)
def test_invalid_resource_does_not_publish_silver(store, pipeline, changes, error):
    tables, _, state, _ = pipeline
    state["items"] = [item(**changes)]
    run(pipeline, 0)
    with pytest.raises(ValueError, match=error):
        run(pipeline, 1)
    assert store.rows(tables["azure_carbon_silver"]) == []
    assert store.rows(tables["finops_carbon_gold"]) == []


@pytest.mark.parametrize(
    "payload,error",
    [
        ([], "INVALID_RESPONSE"),
        ({"value": {}}, "INVALID_RESPONSE"),
        (response([], subscriptionAccessDecisionList=[]), "ACCESS_NOT_CONFIRMED"),
        (
            response(
                [],
                subscriptionAccessDecisionList=[
                    {"subscriptionId": OTHER, "decision": "Allowed"}
                ],
            ),
            "ACCESS_NOT_CONFIRMED",
        ),
        (response([], skipToken=123), "INVALID_PAGINATION"),
    ],
)
def test_invalid_api_response_is_rejected(payload, error):
    client = AzureCarbonClient(
        AzureCarbonSettings(_env_file=None),
        lambda: "fake",
        httpx.Client(
            transport=httpx.MockTransport(
                lambda request: httpx.Response(200, json=payload)
            )
        ),
    )
    try:
        with pytest.raises((TypeError, ValueError), match=error):
            client.pages(SUB, DAY, "scope1_kg")
    finally:
        client.close()


def test_page_limit_and_non_retryable_denial():
    calls = []

    def handler(request):
        calls.append(request)
        return httpx.Response(200, json=response([], skipToken=str(len(calls))))

    config = AzureCarbonSettings(_env_file=None, azure_carbon_max_pages=1)
    client = AzureCarbonClient(
        config, lambda: "fake", httpx.Client(transport=httpx.MockTransport(handler))
    )
    try:
        with pytest.raises(ValueError, match="MAX_PAGES_EXCEEDED"):
            client.pages(SUB, DAY, "scope1_kg")
        assert len(calls) == 1
    finally:
        client.close()
    calls.clear()

    def denied(request):
        calls.append(request)
        return httpx.Response(403)

    client = AzureCarbonClient(
        config, lambda: "fake", httpx.Client(transport=httpx.MockTransport(denied))
    )
    try:
        with pytest.raises(ValueError, match="HTTP_403"):
            client.pages(SUB, DAY, "scope1_kg")
        assert len(calls) == 1
    finally:
        client.close()


def test_month_boundary_and_transport_failure(pipeline, monkeypatch):
    jobs = pipeline[1]
    for day in (date(2026, 1, 2), date(9999, 1, 1)):
        with pytest.raises(ValueError):
            jobs[0].extractor.extract(BatchExecutionContext("MANUAL", day, 1, uuid4()))
    monkeypatch.setattr(
        "finops_batches.providers.azure.carbon.time.sleep", lambda _: None
    )

    def broken(request):
        raise httpx.ReadTimeout("simulated")

    client = AzureCarbonClient(
        AzureCarbonSettings(_env_file=None, azure_carbon_max_attempts=2),
        lambda: "fake",
        httpx.Client(transport=httpx.MockTransport(broken)),
    )
    try:
        with pytest.raises(ValueError, match="TRANSPORT_FAILED"):
            client.pages(SUB, DAY, "scope1_kg")
    finally:
        client.close()


def test_multiple_subscriptions_keep_separate_grains():
    from finops_batches.providers.azure.carbon import (
        AzureCarbonBronzeExtractor,
        AzureCarbonTransformer,
    )

    def handler(request):
        subscription = json.loads(request.content)["subscriptionList"][0]
        value = item(
            subscriptionId=subscription,
            resourceId=f"/subscriptions/{subscription}/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/a",
            latestMonthEmissions=1,
        )
        return httpx.Response(
            200,
            json={
                "subscriptionAccessDecisionList": [
                    {"subscriptionId": subscription, "decision": "Allowed"}
                ],
                "value": [value],
            },
        )

    client = AzureCarbonClient(
        AzureCarbonSettings(_env_file=None),
        lambda: "fake",
        httpx.Client(transport=httpx.MockTransport(handler)),
    )
    extractor = AzureCarbonBronzeExtractor(client, [SUB, OTHER])
    try:
        bronze = extractor.extract(BatchExecutionContext("MANUAL", DAY, 1, uuid4()))
        assert len(bronze) == 9
        bronze[0]["_carbon_month"] = "SILVER"
        silver = AzureCarbonTransformer().transform(bronze)
        assert {row["resource_scope_id"] for row in silver[1:]} == {SUB, OTHER}
        assert all(row["total_market_kg"] == Decimal(1) for row in silver[1:])
    finally:
        extractor.close()


def test_one_denied_subscription_preserves_all_previous_azure_data(store, pipeline):
    tables, jobs, _state, _ = pipeline
    for index in range(3):
        run(pipeline, index)
    before = store.rows(tables["finops_carbon_gold"])
    state_before = store.rows(tables["finops_carbon_month_state"])
    jobs[0].extractor.subscriptions = [SUB, OTHER]
    with pytest.raises(ValueError, match="ACCESS_NOT_CONFIRMED"):
        run(pipeline, 0)
    assert store.rows(tables["finops_carbon_gold"]) == before
    assert store.rows(tables["finops_carbon_month_state"]) == state_before


@pytest.mark.parametrize("mode", ["omit_decisions", "null_decisions"])
def test_optional_decision_list_preserves_real_data_and_empty_guard(
    store, pipeline, mode
):
    tables, _, state, _ = pipeline
    state["mode"] = mode
    assert [run(pipeline, index) for index in range(3)] == [4, 1, 1]
    before = store.rows(tables["finops_carbon_gold"])
    assert before[0]["total_market_kg"] == Decimal("1.2")
    state["items"] = []
    with pytest.raises(ValueError, match="EMPTY_MONTH"):
        run(pipeline, 0)
    assert store.rows(tables["finops_carbon_gold"]) == before


@pytest.mark.parametrize(
    "changes",
    [
        {"subscriptionId": OTHER},
        {"resourceId": "/unexpected"},
        {"subscriptionId": None},
        {"dataType": "ItemDetailsData"},
    ],
)
def test_missing_decisions_require_resource_subscription_evidence(
    store, pipeline, changes
):
    tables, _, state, _ = pipeline
    run(pipeline, 0)
    before = store.rows(tables["azure_carbon_bronze"])
    state["mode"] = "omit_decisions"
    state["items"] = [item(**changes)]
    with pytest.raises(ValueError, match="RESOURCE_SCOPE_NOT_CONFIRMED"):
        run(pipeline, 0)
    assert store.rows(tables["azure_carbon_bronze"]) == before


@pytest.mark.parametrize("status", [400, 401, 403])
def test_http_errors_show_azure_reason_without_bearer_token(status):
    token = "private-bearer-token"
    transport = httpx.MockTransport(
        lambda request: httpx.Response(
            status,
            json={
                "error": {"code": "InvalidRequest", "message": f"Explanation\n{token}"},
            },
        )
    )
    client = AzureCarbonClient(
        AzureCarbonSettings(_env_file=None),
        lambda: token,
        httpx.Client(transport=transport),
    )
    try:
        with pytest.raises(ValueError, match=f"HTTP_{status}") as error:
            client.pages(SUB, DAY, "scope1_kg")
        assert "InvalidRequest: Explanation [redacted]" in str(error.value)
        assert token not in str(error.value)
        assert "\n" not in str(error.value)
    finally:
        client.close()
