"""Production factory chain against isolated SQL: replay, late data and retraction."""

from __future__ import annotations

import re
from datetime import timedelta
from decimal import Decimal
from pathlib import Path
from unittest.mock import MagicMock
from uuid import uuid4

import pytest
from sqlalchemy.exc import IntegrityError

from finops_batches import bootstrap
from finops_batches.application import (
    sponsorship_focus_job,
    sponsorship_usage_gold_job,
    sponsorship_usage_silver_job,
)
from finops_batches.config import Settings
from finops_batches.domain.models import BatchExecutionContext
from finops_batches.providers.azure.sponsorship_client import UsageAggregatesPage

from . import helpers
from .helpers import DAY, NOW, Store, find_ddl_file
from .test_provider_normalization import usage


@pytest.fixture
def pipeline(store: Store, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
    tables = {}
    sql = re.sub(
        r"--[^\n]*", "", find_ddl_file("047_azure_usage_snapshots.sql").read_text()
    )
    for index, statement in enumerate(sql.split(";")):
        if statement.strip().startswith("CREATE TABLE"):
            path = tmp_path / f"snapshot_{index}.sql"
            path.write_text(statement)
            with monkeypatch.context() as patch:
                patch.setattr(
                    helpers, "find_ddl_file", lambda *a, target=path, **kw: target
                )
                table = store.ddl(path.name)
                tables[table.name] = table
    store.insert(tables["azure_sponsorship_pipeline_state"], id=1, revision=0)
    for name in (
        "000_create_azure_sponsorship_billing_bronze_raw.sql",
        "001_create_azure_sponsorship_usage_silver.sql",
        "002_create_azure_sponsorship_focus_silver.sql",
        "003_create_azure_sponsorship_usage_gold.sql",
        "011_create_azure_sponsorship_rate_card_silver.sql",
        "013_create_azure_retail_prices_silver.sql",
    ):
        table = store.ddl(name)
        tables[table.name] = table
    store.insert(
        tables["azure_sponsorship_rate_card_silver"],
        subscription_id="sub",
        meter_id="m",
        offer_durable_id="offer",
        currency="EUR",
        region_info="FR",
        effective_date=NOW - timedelta(days=30),
        unit="Hours",
        unit_price=Decimal(2),
    )
    client = MagicMock(api_version="2015-06-01-preview")
    monkeypatch.setattr(bootstrap, "AzureArmTokenProvider", MagicMock())
    monkeypatch.setattr(
        bootstrap, "AzureSponsorshipUsageClient", MagicMock(return_value=client)
    )
    telemetry = MagicMock()
    monkeypatch.setattr(
        bootstrap.DataTelemetryClient, "from_yaml", MagicMock(return_value=telemetry)
    )
    settings = Settings(
        _env_file=None,
        finops_database_url=store.url,
        azure_tenant_id="test",
        azure_client_id="test",
        azure_client_secret="test",
        azure_subscription_id="sub",
        azure_rate_card_offer_durable_id="offer",
        azure_rate_card_currency="EUR",
        azure_rate_card_region_info="FR",
        azure_retail_prices_currency_code="EUR",
    )
    builders = [
        bootstrap.build_azure_sponsorship_job,
        sponsorship_usage_silver_job.build_azure_sponsorship_usage_silver_job,
        sponsorship_focus_job.build_azure_sponsorship_focus_job,
        sponsorship_usage_gold_job.build_azure_sponsorship_usage_gold_job,
    ]
    jobs = [builder(settings) for builder in builders]
    yield tables, jobs, client, telemetry
    for job in jobs:
        job.close()


def run(job, day=DAY):
    return job.run(BatchExecutionContext("MANUAL", day, 1, uuid4()))


def payload(identifier="one", *, quantity="3", age=0):
    value = usage(
        {
            "quantity": quantity,
            "unit": "Hours",
            "usageStartTime": (NOW - timedelta(days=1 + age)).isoformat(),
            "usageEndTime": (NOW - timedelta(days=age)).isoformat(),
        }
    )
    value["id"] = identifier
    return value


def acquire(pipeline, objects, day=DAY):
    _, jobs, client, _ = pipeline
    client.list_usage_aggregate_pages.return_value = [
        UsageAggregatesPage("https://example.invalid/usage", {"value": objects})
    ]
    return run(jobs[0], day)


def project(pipeline, day=DAY):
    _, jobs, _, _ = pipeline
    return [run(job, day) for job in jobs[1:]]


def test_three_runs_keep_n_then_n_plus_one_without_double_counting(store, pipeline):
    tables, jobs, _, telemetry = pipeline
    assert acquire(pipeline, [payload()]) == 1
    assert project(pipeline) == [1, 1, 1]
    initial = store.rows(tables["azure_sponsorship_usage_silver"])[0]
    assert acquire(pipeline, [payload()]) == 1
    assert project(pipeline) == [1, 1, 1]
    repeated = store.rows(tables["azure_sponsorship_usage_silver"])[0]
    assert repeated["quantity"] == initial["quantity"] == Decimal(3)
    assert repeated["source_payload_hash"] == initial["source_payload_hash"]
    assert repeated["source_bronze_id"] != initial["source_bronze_id"]
    assert (
        acquire(pipeline, [payload(quantity="4"), payload("late", quantity="2")]) == 2
    )
    assert project(pipeline) == [2, 2, 1]
    assert len(store.rows(tables["azure_sponsorship_billing_bronze"])) == 4
    assert len(store.rows(tables["azure_sponsorship_usage_silver"])) == 2
    assert len(store.rows(tables["azure_sponsorship_focus_silver"])) == 2
    gold = store.rows(tables["azure_sponsorship_usage_gold"])
    assert len(gold) == 1
    assert gold[0]["source_line_count"] == 2 and gold[0][
        "consumed_quantity"
    ] == Decimal(6)
    assert gold[0]["valued_cost"] == Decimal(12)
    # A Silver replay without a new acquisition also succeeds.
    assert run(jobs[1]) == 2
    assert telemetry.start_run.call_count == 13


def test_removed_usage_dates_and_valid_empty_snapshot_retract_gold(store, pipeline):
    tables, _, _, _ = pipeline
    acquire(pipeline, [payload(), payload("older", age=3)])
    assert project(pipeline) == [2, 2, 2]
    acquire(pipeline, [payload()])
    assert project(pipeline) == [1, 1, 1]
    gold = store.rows(tables["azure_sponsorship_usage_gold"])
    assert len(gold) == 1 and gold[0]["business_date"] == DAY
    acquire(pipeline, [])
    assert project(pipeline) == [0, 0, 0]
    for name in ("usage_silver", "focus_silver", "usage_gold"):
        assert not store.rows(tables["azure_sponsorship_" + name])
    assert len(store.rows(tables["azure_sponsorship_billing_bronze"])) == 3
    # Replay empty is still an explicit deletion, not a fabricated zero-cost row.
    assert project(pipeline) == [0, 0, 0]


def test_reporting_day_keeps_late_usage_and_other_reporting_days(store, pipeline):
    tables, _, _, _ = pipeline
    acquire(pipeline, [payload(age=4)])
    project(pipeline)
    acquire(pipeline, [payload("other", age=4)], DAY + timedelta(days=1))
    project(pipeline, DAY + timedelta(days=1))
    acquire(pipeline, [payload(age=4, quantity="5")])
    project(pipeline)
    focus = store.rows(tables["azure_sponsorship_focus_silver"])
    assert len(focus) == 2
    assert {row["business_date"] for row in focus} == {DAY, DAY + timedelta(days=1)}
    gold = {
        row["business_date"]: row["consumed_quantity"]
        for row in store.rows(tables["azure_sponsorship_usage_gold"])
    }
    assert gold == {DAY - timedelta(days=4): Decimal(8)}


def test_failed_api_or_transform_keeps_previous_materialization(store, pipeline):
    tables, jobs, client, _ = pipeline
    acquire(pipeline, [payload()])
    project(pipeline)
    original = store.rows(tables["azure_sponsorship_usage_silver"])
    snapshots = store.rows(tables["azure_sponsorship_snapshot"])

    def pages(*args):
        yield UsageAggregatesPage(
            "https://example.invalid/usage", {"value": [payload("partial")]}
        )
        raise ValueError("last page failed")

    client.list_usage_aggregate_pages.side_effect = pages
    with pytest.raises(ValueError, match="last page"):
        run(jobs[0])
    assert store.rows(tables["azure_sponsorship_snapshot"]) == snapshots
    assert len(store.rows(tables["azure_sponsorship_billing_bronze"])) == 1
    client.list_usage_aggregate_pages.side_effect = None
    acquire(pipeline, [{"properties": {"instanceData": "invalid JSON"}}])
    with pytest.raises(ValueError, match="JSON"):
        run(jobs[1])
    assert store.rows(tables["azure_sponsorship_usage_silver"]) == original


def test_stale_extraction_and_failed_insert_roll_back_everything(store, pipeline):
    tables, jobs, _, _ = pipeline
    acquire(pipeline, [payload()])
    project(pipeline)
    context = BatchExecutionContext("MANUAL", DAY, 1, uuid4())
    records = jobs[1].transformer.transform(jobs[1].extractor.extract(context))
    jobs[1]._apply_execution_metadata(records, context=context)
    acquire(pipeline, [payload(quantity="9")])
    original = store.rows(tables["azure_sponsorship_usage_silver"])
    with pytest.raises(ValueError, match="STALE"):
        jobs[1].loader.load(records)
    assert store.rows(tables["azure_sponsorship_usage_silver"]) == original
    records = jobs[1].transformer.transform(jobs[1].extractor.extract(context))
    jobs[1]._apply_execution_metadata(records, context=context)
    # Duplicate source lineage fails AFTER DELETE: transaction must restore old data.
    records.append(dict(records[1]))
    before = store.rows(tables["azure_sponsorship_snapshot"])
    with pytest.raises(IntegrityError):
        jobs[1].loader.load(records)
    assert store.rows(tables["azure_sponsorship_usage_silver"]) == original
    assert store.rows(tables["azure_sponsorship_snapshot"]) == before


def test_latest_snapshot_per_subscription_and_count_guard(store, pipeline):
    tables, jobs, _, _ = pipeline
    acquire(pipeline, [payload()])
    marker = {
        "_azure_snapshot": "BRONZE",
        "business_date": DAY,
        "scope_id": "other",
        "ingestion_run_id": str(uuid4()),
    }
    other = dict(store.rows(tables["azure_sponsorship_billing_bronze"])[0])
    for field in ("id", "created_at"):
        other.pop(field)
    other.update(scope_id="other", ingestion_run_id=marker["ingestion_run_id"])
    assert jobs[0].loader.load([marker, other]) == 1
    assert run(jobs[1]) == 2
    acquire(pipeline, [])
    assert run(jobs[1]) == 1  # other subscription survives an empty sub snapshot
    with store.engine.begin() as conn:
        conn.execute(
            tables["azure_sponsorship_snapshot"]
            .update()
            .where(tables["azure_sponsorship_snapshot"].c.scope_id == "other")
            .values(row_count=99)
        )
    with pytest.raises(ValueError, match="COUNT_MISMATCH"):
        run(jobs[1])


def test_missing_snapshot_does_not_clear_silver(store, pipeline):
    tables, jobs, _, _ = pipeline
    with pytest.raises(ValueError, match="SNAPSHOT_MISSING"):
        run(jobs[1])
    assert not store.rows(tables["azure_sponsorship_usage_silver"])


def test_downstream_requires_fresh_upstream_snapshot(store, pipeline):
    tables, jobs, _, _ = pipeline
    acquire(pipeline, [payload()])
    project(pipeline)
    acquire(pipeline, [payload(quantity="7")])
    with pytest.raises(ValueError, match="OUTDATED.*USAGE"):
        run(jobs[2])
    with pytest.raises(ValueError, match="OUTDATED"):
        run(jobs[3])
    assert store.rows(tables["azure_sponsorship_usage_gold"])[0][
        "consumed_quantity"
    ] == Decimal(3)
    run(jobs[1])
    with pytest.raises(ValueError, match="OUTDATED.*FOCUS"):
        run(jobs[3])
    run(jobs[2])
    run(jobs[3])
    assert store.rows(tables["azure_sponsorship_usage_gold"])[0][
        "consumed_quantity"
    ] == Decimal(7)


def test_focus_rollback_preserves_old_rows_and_retraction_dates(store, pipeline):
    tables, jobs, _, _ = pipeline
    acquire(pipeline, [payload()])
    project(pipeline)
    acquire(pipeline, [payload("new", age=2)])
    run(jobs[1])
    context = BatchExecutionContext("MANUAL", DAY, 1, uuid4())
    records = jobs[2].transformer.transform(jobs[2].extractor.extract(context))
    jobs[2]._apply_execution_metadata(records, context=context)
    before = {
        name: store.rows(tables[name])
        for name in (
            "azure_sponsorship_focus_silver",
            "azure_sponsorship_snapshot",
            "azure_sponsorship_gold_refresh_day",
        )
    }
    records.append(dict(records[1]))
    with pytest.raises(IntegrityError):
        jobs[2].loader.load(records)
    assert before == {name: store.rows(tables[name]) for name in before}


def test_gold_rejects_stale_or_unsafe_empty_publication(store, pipeline):
    tables, jobs, _, _ = pipeline
    acquire(pipeline, [payload()])
    project(pipeline)
    context = BatchExecutionContext("MANUAL", DAY, 1, uuid4())
    records = jobs[3].transformer.transform(jobs[3].extractor.extract(context))
    jobs[3]._apply_execution_metadata(records, context=context)
    acquire(pipeline, [payload(quantity="9")])
    before = store.rows(tables["azure_sponsorship_usage_gold"])
    with pytest.raises(ValueError, match="STALE"):
        jobs[3].loader.load(records)
    assert store.rows(tables["azure_sponsorship_usage_gold"]) == before
    with pytest.raises(ValueError, match="MARKER_REQUIRED"):
        jobs[3].loader.load([])
    assert store.rows(tables["azure_sponsorship_usage_gold"]) == before
