"""Historical pricing immutability, replay and transactional rollback."""

from datetime import timedelta

import pytest
from sqlalchemy import Column, DateTime, Integer, MetaData, String, Table, select
from sqlalchemy.exc import IntegrityError

from finops_batches.domain.models import Record
from finops_batches.exceptions import BatchExecutionError
from finops_batches.infrastructure.common import (
    IdentityTransformer,
    SqlAlchemyTableLoader,
)
from finops_batches.infrastructure.rate_card_history_loader import (
    AzureRateCardHistoryLoader,
)
from finops_batches.infrastructure.retail_price_history_loader import (
    AzureRetailPriceHistoryLoader,
)
from finops_batches.infrastructure.sponsorship_focus_loader import (
    AzureSponsorshipFocusLoader,
)
from finops_batches.providers.azure.focus_loader import FocusCostUsageDailyLoader
from finops_batches.providers.azure.pricing_silver_common import (
    HistoricalPricingSilverLoader,
)

from .helpers import NOW, Store


def test_rate_card_replay_preserves_first_observation_and_detects_mutation(
    store: Store,
) -> None:
    table = store.ddl("011_create_azure_sponsorship_rate_card_silver.sql")
    record = store.insert(table, source_hash="a", unit_price=2)
    loader = AzureRateCardHistoryLoader(database_url=store.url, table_name=table.name)
    try:
        assert loader.load([]) == 0
        assert (
            loader.load([dict(record) | {"last_seen_at": NOW + timedelta(days=1)}]) == 0
        )
        (row,) = store.rows(table)
        assert row["unit_price"] == 2 and row["first_seen_at"] == NOW
        assert row["last_seen_at"] == NOW + timedelta(days=1)
        fresh = dict(record) | {"meter_id": "new", "source_hash": "new"}
        with pytest.raises(ValueError, match="rétroactive"):
            loader.load([fresh, dict(record) | {"source_hash": "changed"}])
        assert len(store.rows(table)) == 1
        assert loader.load([fresh]) == 1
    finally:
        loader.close()


@pytest.mark.parametrize("url,name", [("", "table"), ("sqlite://", "")])
def test_rate_card_required_settings(url: str, name: str) -> None:
    with pytest.raises(ValueError):
        AzureRateCardHistoryLoader(database_url=url, table_name=name)


def test_retail_history_replay_and_mutation_diff(store: Store) -> None:
    # The legacy loader's expected columns are intentionally exercised separately.
    table = Table(
        "retail_history",
        MetaData(),
        Column("id", Integer, primary_key=True),
        Column("price_key", String, unique=True),
        Column("source_hash", String),
        Column("raw_payload", String),
        Column("first_seen_at", DateTime),
        Column("last_seen_at", DateTime),
        Column("ingestion_run_id", String),
    )
    table.create(store.engine)
    loader = AzureRetailPriceHistoryLoader(
        database_url=store.url, table_name=table.name
    )
    record: Record = {
        "price_key": "key",
        "source_hash": "a",
        "raw_payload": '{"price":1}',
        "first_seen_at": NOW,
        "last_seen_at": NOW,
        "ingestion_run_id": "one",
    }
    try:
        assert loader.load([]) == 0
        assert loader.load([record]) == 1
        assert (
            loader.load([dict(record) | {"last_seen_at": NOW + timedelta(days=1)}]) == 1
        )
        with pytest.raises(ValueError, match="RETROACTIVE_MUTATION.*price"):
            loader.load(
                [dict(record) | {"source_hash": "b", "raw_payload": '{"price":2}'}]
            )
        (row,) = store.rows(table)
        assert row["raw_payload"] == '{"price":1}'
        assert row["first_seen_at"] == NOW
        for field in ("price_key", "source_hash"):
            with pytest.raises(ValueError, match=field):
                loader.load([dict(record) | {field: None}])
    finally:
        loader.close()
    with pytest.raises(ValueError):
        AzureRetailPriceHistoryLoader(database_url="")


@pytest.mark.parametrize("semantic", [False, True])
def test_historical_silver_hash_contract_and_rollback(
    store: Store, semantic: bool
) -> None:
    filename = (
        "013_create_azure_retail_prices_silver.sql"
        if semantic
        else "011_create_azure_sponsorship_rate_card_silver.sql"
    )
    table = store.ddl(filename)
    original = store.insert(
        table, source_hash="raw1", **({"pricing_hash": "economic1"} if semantic else {})
    )
    natural_key = ["price_key"] if semantic else ["meter_id"]
    loader = HistoricalPricingSilverLoader(
        database_url=store.url,
        table_name=table.name,
        natural_key=natural_key,
        mutation_error_code="IMMUTABLE",
    )
    try:
        assert loader.load([]) == 0
        update = dict(original) | {
            "last_seen_at": NOW + timedelta(days=1),
            "source_bronze_id": 9,
        }
        if semantic:
            update["source_hash"] = "different-raw-same-price"
        assert loader.load([update]) == 1
        (row,) = store.rows(table)
        assert row["source_bronze_id"] == 9
        assert row["first_seen_at"] == NOW
        mutation = dict(update) | {
            ("pricing_hash" if semantic else "source_hash"): "new-price"
        }
        fresh = dict(original) | {natural_key[0]: "new-key"}
        with pytest.raises(BatchExecutionError, match="IMMUTABLE"):
            loader.load([fresh, mutation])
        assert len(store.rows(table)) == 1
        with pytest.raises(ValueError, match="hash"):
            loader.load(
                [dict(update) | {("pricing_hash" if semantic else "source_hash"): ""}]
            )
        assert loader.load([fresh]) == 1
    finally:
        loader.close()


def test_focus_upsert_preserves_other_rows_and_rejects_unknown_columns(
    store: Store,
) -> None:
    table = store.ddl("002_create_azure_sponsorship_focus_silver.sql")
    loader = AzureSponsorshipFocusLoader(database_url=store.url)
    base = store.insert(table, RowId="row1", BilledCost=1)
    try:
        assert loader.load([]) == 0
        assert (
            loader.load(
                [dict(base) | {"BilledCost": 9}, dict(base) | {"RowId": "row2"}]
            )
            == 2
        )
        values = {row["RowId"]: row["BilledCost"] for row in store.rows(table)}
        assert values == {"row1": 9, "row2": 1}
        with pytest.raises(ValueError, match="Colonnes"):
            loader.load([dict(base) | {"unknown": 1}])
        with pytest.raises(ValueError, match="RowId"):
            loader.load([dict(base) | {"RowId": ""}])
    finally:
        loader.close()
    for kwargs in ({"database_url": ""}, {"database_url": store.url, "table_name": ""}):
        with pytest.raises(ValueError):
            AzureSponsorshipFocusLoader(**kwargs)


def test_generic_loader_transaction_and_identity_copy(store: Store) -> None:
    table = Table(
        "simple",
        MetaData(),
        Column("id", Integer, primary_key=True),
        Column("value", String, nullable=False),
    )
    table.create(store.engine)
    loader = SqlAlchemyTableLoader(database_url=store.url, table_name=table.name)
    try:
        assert loader.load([]) == 0
        original: list[Record] = [{"id": 1, "value": "one"}]
        copied = IdentityTransformer().transform(original)
        assert copied == original and copied[0] is not original[0]
        assert loader.load(copied) == 1
        with pytest.raises(IntegrityError):
            loader.load([{"id": 2, "value": "two"}, {"id": 1, "value": "duplicate"}])
        assert len(store.rows(table)) == 1
    finally:
        loader.close()


def test_legacy_daily_focus_loader_only_replaces_the_requested_day(
    store: Store,
) -> None:
    table = Table(
        "daily_focus",
        MetaData(),
        Column("ChargePeriodStart", DateTime, primary_key=True),
        Column("cost", Integer),
    )
    table.create(store.engine)
    loader = FocusCostUsageDailyLoader(database_url=store.url, table_name=table.name)
    try:
        assert loader.load([]) == 0
        assert loader.load([{"ChargePeriodStart": NOW, "cost": 1}]) == 1
        assert (
            loader.load([{"ChargePeriodStart": NOW + timedelta(days=1), "cost": 2}])
            == 1
        )
        assert loader.load([{"ChargePeriodStart": NOW, "cost": 9}]) == 1
        with pytest.raises(TypeError):
            loader.load([{"ChargePeriodStart": None}])
        with pytest.raises(ValueError):
            loader.load(
                [
                    {"ChargePeriodStart": NOW},
                    {"ChargePeriodStart": NOW + timedelta(days=1)},
                ]
            )
        with store.engine.connect() as conn:
            assert conn.execute(
                select(table.c.cost).order_by(table.c.ChargePeriodStart)
            ).scalars().all() == [9, 2]
    finally:
        loader.close()
