from __future__ import annotations

import json
from datetime import UTC, date, datetime
from decimal import Decimal
from typing import cast

import pytest

from finops_batches.providers.gcp.focus import (
    GcpFocusTransformationError,
    GcpFocusTransformer,
)


def _payload() -> dict[str, object]:
    return {
        "billing_account_id": "01FBF0-7A5A05-1309B5",
        "invoice": {
            "month": "202611",
            "publisher_type": "GOOGLE",
        },
        "cost_type": "regular",
        "service": {
            "id": "6F81-5844-456A",
            "description": "Compute Engine",
        },
        "sku": {
            "id": "sku-1",
            "description": "N2 Instance Core",
        },
        "usage_start_time": "2026-11-01T00:00:00+00:00",
        "usage_end_time": "2026-11-01T01:00:00+00:00",
        "export_time": "2026-11-02T03:00:00+00:00",
        "project": {
            "id": "prj-a1001-dev-01",
            "name": "AI Data and Ingest DEV",
        },
        "location": {
            "region": "europe-west1",
            "zone": "europe-west1-b",
        },
        "resource": {
            "global_name": "//compute.googleapis.com/projects/p/zones/z/instances/i",
            "name": "instance-1",
        },
        "cost": "10.00",
        "cost_at_list": "12.00",
        "currency": "EUR",
        "currency_conversion_rate": "1",
        "usage": {
            "amount": "2",
            "unit": "hour",
            "amount_in_pricing_units": "2",
            "pricing_unit": "hour",
        },
        "credits": [
            {
                "type": "DISCOUNT",
                "name": "Example discount",
                "amount": "-3.00",
            }
        ],
        "price": {
            "list_price": "6.00",
            "effective_price": "5.00",
        },
        "consumption_model": {
            "id": "7754-699E-0EBF",
            "description": "Default",
        },
        "subscription": {},
        "seller_name": "Google",
        "labels": [{"key": "env", "value": "dev"}],
    }


def test_transform_native_google_usage_to_focus_14() -> None:
    result = GcpFocusTransformer().transform(
        _payload(),
        business_date=date(2026, 11, 1),
        ingestion_run_id="run-1",
        generated_at=datetime(2026, 11, 4, 10, 0, tzinfo=UTC),
    )

    assert result["ProviderName"] == "Google Cloud"
    assert result["PublisherName"] == "Google Cloud"
    assert result["ServiceProviderName"] == "Google Cloud"
    assert result["HostProviderName"] == "Google Cloud"
    assert result["InvoiceIssuerName"] is None
    assert result["BillingAccountName"] is None
    assert result["ServiceName"] == "Compute Engine"
    assert result["ServiceCategory"] == "Compute"
    assert result["x_ServiceCategorySource"] == "EXACT_SERVICE_MAPPING"
    assert result["ListCost"] == Decimal("12.00")
    assert result["ContractedCost"] == Decimal("10.00")
    assert result["BilledCost"] == Decimal("7.00")
    assert result["EffectiveCost"] == Decimal("7.00")
    assert result["x_ListCostSource"] == "GCP_COST_AT_LIST"
    assert result["PricingCategory"] == "Standard"
    assert result["x_SellerName"] == "Google"
    assert result["x_FocusConformanceStatus"] == "PARTIAL"
    assert json.loads(str(result["x_FocusConformanceGaps"])) == [
        "BillingAccountName",
        "InvoiceIssuerName",
    ]
    assert json.loads(str(result["x_Credits"]))[0]["amount"] == "-3.00"


def test_transform_uses_billing_account_reference() -> None:
    result = GcpFocusTransformer().transform(
        _payload(),
        business_date=date(2026, 11, 1),
        ingestion_run_id="run-reference",
        billing_account_name="GentleIT Billing Account",
        billing_account_name_source="CLOUD_BILLING_API",
        invoice_issuer_name="Example Legal Invoice Issuer",
        invoice_issuer_source="CONTRACT",
    )

    assert result["BillingAccountName"] == "GentleIT Billing Account"
    assert result["InvoiceIssuerName"] == "Example Legal Invoice Issuer"
    assert result["x_BillingAccountNameSource"] == "CLOUD_BILLING_API"
    assert result["x_InvoiceIssuerSource"] == "CONTRACT"
    assert result["x_FocusConformanceStatus"] == "READY_FOR_CONFORMANCE_REVIEW"
    assert json.loads(str(result["x_FocusConformanceGaps"])) == []


def test_transform_tax_uses_invoice_service_and_list_cost_fallback() -> None:
    payload = _payload()
    payload["cost_type"] = "tax"
    payload["service"] = {}
    payload["sku"] = {}
    payload["project"] = {}
    payload["resource"] = {}
    payload["location"] = {}
    payload["cost"] = "5.17"
    payload["cost_at_list"] = None
    payload["credits"] = []
    payload["usage"] = {}
    payload["price"] = {}
    payload["seller_name"] = "Google Cloud"

    result = GcpFocusTransformer().transform(
        payload,
        business_date=date(2026, 11, 1),
        ingestion_run_id="run-tax",
    )

    assert result["ChargeCategory"] == "Tax"
    assert result["ChargeDescription"] == "Tax"
    assert result["ServiceName"] == "Invoice"
    assert result["ServiceCategory"] == "Other"
    assert result["HostProviderName"] is None
    assert result["ListCost"] == Decimal("5.17")
    assert result["ContractedCost"] == Decimal("5.17")
    assert result["BilledCost"] == Decimal("5.17")
    assert result["x_ListCostSource"] == "GCP_COST_FALLBACK"
    assert result["ConsumedQuantity"] == Decimal(0)
    assert result["ConsumedUnit"] == "N/A"


def test_transform_rounding_error_to_adjustment() -> None:
    payload = _payload()
    payload["cost_type"] = "rounding_error"
    payload["service"] = {}
    payload["sku"] = {}
    payload["cost_at_list"] = None
    payload["cost"] = "-0.004338"
    payload["credits"] = []

    result = GcpFocusTransformer().transform(
        payload,
        business_date=date(2026, 11, 1),
        ingestion_run_id="run-adjustment",
    )

    assert result["ChargeCategory"] == "Adjustment"
    assert result["ChargeDescription"] == "Rounding Error"
    assert result["ServiceName"] == "Invoice"
    assert result["ServiceCategory"] == "Other"
    assert result["HostProviderName"] is None


def test_transform_marketplace_seller_becomes_service_provider() -> None:
    payload = _payload()
    payload["seller_name"] = "Third Party Software Ltd"
    invoice = dict(cast(dict[str, object], payload["invoice"]))
    invoice["publisher_type"] = "THIRD_PARTY_RESELLER"
    payload["invoice"] = invoice

    result = GcpFocusTransformer().transform(
        payload,
        business_date=date(2026, 11, 1),
        ingestion_run_id="run-marketplace",
    )

    assert result["ServiceProviderName"] == "Third Party Software Ltd"
    assert result["PublisherName"] == "Third Party Software Ltd"
    assert result["HostProviderName"] is None
    assert result["InvoiceIssuerName"] is None
    assert result["x_InvoicePublisherType"] == "THIRD_PARTY_RESELLER"


def test_transform_committed_consumption_model() -> None:
    payload = _payload()
    consumption_model = dict(cast(dict[str, object], payload["consumption_model"]))
    consumption_model["applied_subscription_instance_id"] = "commitment-123"
    payload["consumption_model"] = consumption_model

    result = GcpFocusTransformer().transform(
        payload,
        business_date=date(2026, 11, 1),
        ingestion_run_id="run-cud",
    )

    assert result["PricingCategory"] == "Committed"
    assert result["x_AppliedSubscriptionInstanceId"] == "commitment-123"


@pytest.mark.parametrize(
    ("service_name", "expected_category"),
    [
        ("Cloud Composer", "Integration"),
        ("BigQuery Storage API", "Analytics"),
    ],
)
def test_recently_discovered_services_are_mapped(
    service_name: str,
    expected_category: str,
) -> None:
    payload = _payload()
    service = dict(cast(dict[str, object], payload["service"]))
    service["description"] = service_name
    payload["service"] = service

    result = GcpFocusTransformer().transform(
        payload,
        business_date=date(2026, 11, 1),
        ingestion_run_id="run-known-service",
    )

    assert result["ServiceCategory"] == expected_category
    assert result["x_ServiceCategorySource"] == "EXACT_SERVICE_MAPPING"


def test_unknown_service_category_falls_back_to_other() -> None:
    payload = _payload()
    service = dict(cast(dict[str, object], payload["service"]))
    service["description"] = "Future Quantum Service"
    payload["service"] = service

    result = GcpFocusTransformer().transform(
        payload,
        business_date=date(2026, 11, 1),
        ingestion_run_id="run-unknown-service",
    )

    assert result["ServiceCategory"] == "Other"
    assert result["x_ServiceCategorySource"] == "FALLBACK_OTHER"


def test_invalid_invoice_month_fails() -> None:
    payload = _payload()
    invoice = dict(cast(dict[str, object], payload["invoice"]))
    invoice["month"] = "2026-11"
    payload["invoice"] = invoice

    with pytest.raises(GcpFocusTransformationError, match="YYYYMM"):
        GcpFocusTransformer().transform(
            payload,
            business_date=date(2026, 11, 1),
            ingestion_run_id="run-invalid",
        )
