"""Gold amounts, usage dates, late arrivals and atomic replacements."""

from __future__ import annotations

from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from decimal import Decimal
from pathlib import Path
from uuid import uuid4

import pytest
from sqlalchemy import (
    CheckConstraint,
    Column,
    Date,
    DateTime,
    Integer,
    MetaData,
    Numeric,
    String,
    Table,
    create_engine,
    select,
)
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.schema import SchemaItem

from finops_batches.domain.models import BatchExecutionContext, Record
from finops_batches.infrastructure.sponsorship_usage_gold_loader import (
    AzureSponsorshipUsageGoldLoader,
)
from finops_batches.providers.azure.sponsorship_usage_gold import (
    GOLD_AMOUNTS,
    GOLD_COUNTS,
    GOLD_DIMENSIONS,
    GOLD_LABELS,
    SILVER_COLUMNS,
    AzureSponsorshipUsageGoldExtractor,
    AzureSponsorshipUsageGoldTransformer,
    business_day,
    database_datetime,
    decimal_or_none,
)

DAY = date(2026, 8, 1)
ACQUIRED = date(2026, 8, 3)


def source(**overrides: object) -> Record:
    """Return one Silver line using the actual transformer conventions."""
    record: Record = dict.fromkeys(SILVER_COLUMNS)
    record.update(
        {
            "business_date": DAY,
            "ChargePeriodStart": datetime(2026, 8, 1, tzinfo=UTC),
            "ChargePeriodEnd": datetime(2026, 8, 2, tzinfo=UTC),
            "BillingAccountId": "sub",
            "SubAccountId": "sub",
            "SubAccountName": "Subscription",
            "x_Provider": "Azure",
            "x_BillingModel": "Sponsorship",
            "BillingCurrency": "EUR",
            "ChargeCategory": "Usage",
            "ChargeFrequency": "Usage-Based",
            "SkuId": "meter",
            "SkuMeter": "Usage meter",
            "x_UsageMeterId": "meter",
            "x_SkuMeterId": "meter",
            "RegionId": "westeurope",
            "ConsumedUnit": "Hours",
            "PricingUnit": "Hours",
            "x_PricingSource": "SPONSORSHIP_RATE_CARD",
            "x_PricingConfidence": "CONTRACTUAL",
            "x_RateCardCurrency": "EUR",
            "PricingCurrency": "EUR",
            "ConsumedQuantity": Decimal(2),
            "PricingQuantity": Decimal(2),
            "ContractedCost": Decimal(5),
            "BilledCost": Decimal(5),
            "EffectiveCost": Decimal(5),
            "x_GeneratedAt": datetime(2026, 8, 3, tzinfo=UTC),
            "x_BilledCostBasis": "ESTIMATED_FROM_RATE_CARD",
            "x_RatingReconciliationStatus": "UNVERIFIED",
            "x_FocusComplianceStatus": "PROVISIONAL",
            "_gold_trigger_business_date": ACQUIRED,
        }
    )
    record.update(overrides)
    return record


def transformed(*rows: Record) -> list[Record]:
    """Apply the transformer and the standard logical-run metadata."""
    result = AzureSponsorshipUsageGoldTransformer().transform(rows)
    for row in result:
        row["ingestion_run_id"] = str(uuid4())
    return result


@pytest.fixture
def database(tmp_path: Path) -> Iterator[tuple[str, Engine, Table, Table]]:
    """Create reflected source and target schemas for local transaction tests."""
    url = f"sqlite:///{tmp_path / 'gold.db'}"
    engine = create_engine(url)
    meta = MetaData()
    silver_columns: list[SchemaItem] = []
    for name in SILVER_COLUMNS:
        if name == "business_date":
            silver_columns.append(Column(name, Date))
        elif name in {"ChargePeriodStart", "ChargePeriodEnd", "x_GeneratedAt"}:
            silver_columns.append(Column(name, DateTime))
        elif name in {
            "ConsumedQuantity",
            "PricingQuantity",
            "BilledCost",
            "EffectiveCost",
            "ContractedCost",
            "ListCost",
        }:
            silver_columns.append(Column(name, Numeric(38, 12)))
        else:
            silver_columns.append(Column(name, String(500)))
    silver = Table("azure_sponsorship_focus_silver", meta, *silver_columns)
    gold = Table(
        "azure_sponsorship_usage_gold",
        meta,
        Column("business_date", Date, primary_key=True),
        Column("grain_hash", String(64), primary_key=True),
        *(Column(name, String(500), nullable=False) for name in GOLD_DIMENSIONS),
        *(Column(name, String(500)) for name in GOLD_LABELS),
        *(Column(name, Numeric(38, 12)) for name in GOLD_AMOUNTS),
        *(Column(name, Integer, nullable=False) for name in GOLD_COUNTS),
        Column("source_business_date_min", Date),
        Column("source_business_date_max", Date),
        Column("trigger_business_date", Date),
        Column("source_generated_at_max", DateTime),
        Column("generated_at", DateTime),
        Column("ingestion_run_id", String(36), nullable=False),
        CheckConstraint("valued_cost IS NULL OR valued_cost < 1000"),
    )
    meta.create_all(engine)
    yield url, engine, silver, gold
    engine.dispose()


def test_exact_partial_cost_and_provenance() -> None:
    """Sum high precision values and retain null costs and provisional flags."""
    amount = Decimal("1234567890123456789012345.123456789012")
    rows = transformed(
        source(ContractedCost=amount),
        source(ContractedCost=Decimal("0.000000000001")),
        source(ContractedCost=None),
    )
    (row,) = rows
    assert row["valued_cost"] == Decimal("1234567890123456789012345.123456789013")
    assert row["source_line_count"] == 3
    assert row["valued_line_count"] == 2
    assert row["unpriced_line_count"] == 1
    assert row["retail_fallback_cost"] is None
    assert row["rating_reconciliation_status"] == "UNVERIFIED"
    assert row["focus_compliance_status"] == "PROVISIONAL"


def test_retail_and_unpriced() -> None:
    """Keep public estimates separate and do not value ambiguous matches."""
    rows = transformed(
        source(),
        source(
            x_PricingSource="RETAIL_PRICE_FALLBACK",
            x_RetailCurrency="EUR",
            ContractedCost=None,
            ListCost=Decimal(3),
        ),
        source(
            x_PricingSource="RETAIL_PRICE_AMBIGUOUS",
            ContractedCost=None,
            ListCost=Decimal(9),
        ),
    )
    assert len(rows) == 3
    retail = next(
        row for row in rows if row["pricing_source"] == "RETAIL_PRICE_FALLBACK"
    )
    assert retail["retail_fallback_cost"] == 3
    assert retail["contracted_cost"] is None
    missing = next(
        row for row in rows if row["pricing_source"] == "RETAIL_PRICE_AMBIGUOUS"
    )
    assert missing["valued_cost"] is None
    assert missing["unpriced_line_count"] == 1


@pytest.mark.parametrize(
    "changes",
    [
        {"ConsumedUnit": "GB"},
        {"PricingUnit": "100 Hours"},
        {"RegionId": "eastus"},
        {"BillingCurrency": "USD"},
        {"SkuId": "METER"},
        {"x_UsageMeterId": "another"},
        {"ChargeClass": "Correction"},
        {"x_BilledCostBasis": "Other"},
    ],
)
def test_distinct_grains(changes: dict[str, object]) -> None:
    """Avoid combining incompatible dimensions."""
    assert len(transformed(source(), source(**changes))) == 2


@pytest.mark.parametrize("currency", ["USD", None])
def test_currency_guard(currency: str | None) -> None:
    """A missing or different tariff currency is rejected without inventing FX."""
    (row,) = transformed(source(x_RateCardCurrency=currency, PricingCurrency=None))
    assert row["currency_rejected_line_count"] == 1
    assert row["valued_cost"] is None


def test_currency_fallback_and_zero() -> None:
    """PricingCurrency from the current Silver supplies the currency if needed."""
    (row,) = transformed(source(x_RateCardCurrency=None, ContractedCost=Decimal(0)))
    assert row["valued_cost"] == 0
    assert row["valued_line_count"] == 1


def test_source_dates_and_stable_identity() -> None:
    """Changing an acquisition date does not move the consumption day or its key."""
    (row,) = transformed(source(), source(business_date=ACQUIRED))
    assert row["business_date"] == DAY
    assert row["source_business_date_min"] == DAY
    assert row["source_business_date_max"] == ACQUIRED
    (replay,) = transformed(source())
    assert replay["grain_hash"] == row["grain_hash"]
    (fallback,) = transformed(source(SkuId=None, x_UsageMeterId=None))
    assert fallback["sku_key"] == "METER:meter"


@pytest.mark.parametrize(
    "end", [datetime(2026, 8, 1, tzinfo=UTC), datetime(2026, 8, 3, tzinfo=UTC)]
)
def test_invalid_period(end: datetime) -> None:
    """Refuse non-daily periods instead of arbitrarily allocating their cost."""
    with pytest.raises(ValueError, match="GOLD_NON_DAILY_USAGE"):
        transformed(source(ChargePeriodEnd=end))


def test_invalid_input_and_contexts() -> None:
    """Fail before any load when metadata or amounts are invalid."""
    with pytest.raises(TypeError):
        transformed(source(ContractedCost=0.1))
    with pytest.raises(ValueError, match="Identité"):
        transformed(source(x_UsageMeterId=None, x_SkuMeterId=None))
    with pytest.raises(ValueError, match="obligatoire"):
        transformed(source(ConsumedQuantity=None))
    with pytest.raises(ValueError, match="MULTIPLE_CONTEXTS"):
        transformed(source(), source(_gold_trigger_business_date=DAY))
    with pytest.raises(ValueError, match="obligatoire"):
        transformed(source(SubAccountId=None))
    with pytest.raises(ValueError, match="non fini"):
        decimal_or_none(Decimal("NaN"))
    with pytest.raises(TypeError):
        database_datetime("2026-08-01", "date")
    with pytest.raises(TypeError):
        business_day(None)
    assert business_day("2026-08-01") == DAY
    assert business_day(datetime(2026, 8, 1, tzinfo=UTC)) == DAY
    assert decimal_or_none(None) is None
    assert decimal_or_none("1.25") == Decimal("1.25")


def test_extractor_reloads_complete_late_usage_days(
    database: tuple[str, Engine, Table, Table],
) -> None:
    """A late arrival triggers rebuilding the whole day, not only the new delta."""
    url, engine, silver, _ = database
    records = [
        source(),
        source(business_date=ACQUIRED, ContractedCost=Decimal(3)),
        source(
            business_date=ACQUIRED,
            ChargePeriodStart=datetime(2026, 8, 2, tzinfo=UTC),
            ChargePeriodEnd=datetime(2026, 8, 3, tzinfo=UTC),
        ),
        source(
            business_date=date(2026, 8, 10),
            ChargePeriodStart=datetime(2026, 8, 10, tzinfo=UTC),
            ChargePeriodEnd=datetime(2026, 8, 11, tzinfo=UTC),
        ),
    ]
    with engine.begin() as conn:
        conn.execute(
            silver.insert(),
            [
                {key: value for key, value in row.items() if key in SILVER_COLUMNS}
                for row in records
            ],
        )
    extractor = AzureSponsorshipUsageGoldExtractor(database_url=url)
    try:
        extracted = extractor.extract(
            BatchExecutionContext(
                business_date=ACQUIRED,
                logical_run_id=uuid4(),
                trigger_type="MANUAL",
                attempt_number=1,
            )
        )
        assert len(extracted) == 3
        result = transformed(*extracted)
        usage_days: set[date] = set()
        for row in result:
            usage_day = row["business_date"]
            assert isinstance(usage_day, date)
            usage_days.add(usage_day)
        assert usage_days == {
            DAY,
            DAY + timedelta(days=1),
        }
        first = next(row for row in result if row["business_date"] == DAY)
        assert first["valued_cost"] == 8
    finally:
        extractor.close()


def test_loader_replay_obsolete_groups_and_rollback(
    database: tuple[str, Engine, Table, Table],
) -> None:
    """Replace complete days, preserve unrelated days and roll back failed insertion."""
    url, engine, _, gold = database
    loader = AzureSponsorshipUsageGoldLoader(database_url=url)
    other = source(
        ChargePeriodStart=datetime(2026, 8, 2, tzinfo=UTC),
        ChargePeriodEnd=datetime(2026, 8, 3, tzinfo=UTC),
    )
    try:
        assert loader.load(transformed(source(), source(SkuId="obsolete"), other)) == 3
        assert loader.load(transformed(source(ContractedCost=Decimal(8)))) == 1
        assert loader.load(transformed(source(ContractedCost=Decimal(8)))) == 1
        with pytest.raises(IntegrityError):
            loader.load(transformed(source(ContractedCost=Decimal(2000))))
        with engine.connect() as conn:
            rows = conn.execute(
                select(gold.c.business_date, gold.c.valued_cost).order_by(
                    gold.c.business_date
                )
            ).all()
        assert rows == [(DAY, Decimal(8)), (DAY + timedelta(days=1), Decimal(5))]
    finally:
        loader.close()


def test_loader_guards(database: tuple[str, Engine, Table, Table]) -> None:
    """Reject unsafe payloads before a deletion."""
    url, _, _, _ = database
    loader = AzureSponsorshipUsageGoldLoader(database_url=url)
    (row,) = transformed(source())
    cases: list[tuple[list[Record], str]] = [
        ([], "EMPTY"),
        ([row, row], "DUPLICATE"),
        ([dict(row) | {"unknown": 1}], "absentes"),
        ([dict(row) | {"grain_hash": "short"}], "grain_hash"),
        ([dict(row) | {"ingestion_run_id": None}], "ingestion_run_id"),
        ([dict(row) | {"source_line_count": -1}], "Compteurs"),
        ([dict(row) | {"source_line_count": 3}], "RECONCILIATION"),
    ]
    try:
        for records, message in cases:
            with pytest.raises(ValueError, match=message):
                loader.load(records)
    finally:
        loader.close()


def test_constructor_guards(database: tuple[str, Engine, Table, Table]) -> None:
    """Validate input parameters and reflected schemas."""
    url, _, _, _ = database
    for cls in (AzureSponsorshipUsageGoldExtractor, AzureSponsorshipUsageGoldLoader):
        with pytest.raises(ValueError, match="FINOPS_DATABASE_URL"):
            cls(database_url=" ")
        with pytest.raises(ValueError):
            cls(
                database_url=url,
                table_name=(
                    "azure_sponsorship_usage_gold"
                    if cls is AzureSponsorshipUsageGoldExtractor
                    else "azure_sponsorship_focus_silver"
                ),
            )
