from __future__ import annotations

import json
from datetime import date, datetime
from typing import cast

import pytest

from finops_batches.domain.models import Record
from finops_batches.providers.gcp.focus_silver import GcpFocusSilverTransformer


def _bronze_record() -> Record:
    payload: dict[str, object] = {
        "billing_account_id": "01FBF0-7A5A05-1309B5",
        "invoice": {"month": "202611", "publisher_type": "GOOGLE"},
        "cost_type": "regular",
        "service": {"id": "service-1", "description": "Compute Engine"},
        "sku": {"id": "sku-1", "description": "Compute SKU"},
        "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-1", "name": "Project 1"},
        "location": {"region": "europe-west1", "zone": "europe-west1-b"},
        "resource": {"global_name": "//resource/1", "name": "resource-1"},
        "cost": "2.00",
        "cost_at_list": "2.50",
        "currency": "EUR",
        "usage": {
            "amount": "1",
            "unit": "hour",
            "amount_in_pricing_units": "1",
            "pricing_unit": "hour",
        },
        "credits": [],
        "price": {"list_price": "2.50", "effective_price": "2.00"},
        "consumption_model": {"id": "default", "description": "Default"},
        "subscription": {},
        "seller_name": "Google",
    }

    return cast(
        Record,
        {
            "source_bronze_id": 42,
            "business_date": date(2026, 11, 1),
            "payload": json.dumps(payload),
            "source_payload_hash": "a" * 64,
            "source_ingestion_run_id": "bronze-run-1",
            "source_page_number": 1,
            "source_record_number": 7,
            "source_api_version": "bigquery-detailed-v1",
            "reference_billing_account_name": "GentleIT Billing Account",
            "reference_billing_account_name_source": "CLOUD_BILLING_API",
            "reference_invoice_issuer_name": "Example Legal Invoice Issuer",
            "reference_invoice_issuer_source": "CONTRACT",
        },
    )


def test_transform_adds_reference_and_source_traceability() -> None:
    result = GcpFocusSilverTransformer().transform([_bronze_record()])[0]

    assert result["business_date"] == date(2026, 11, 1)
    assert result["ServiceProviderName"] == "Google Cloud"
    assert result["ServiceCategory"] == "Compute"
    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 result["x_SourceBronzeId"] == 42
    assert result["x_SourcePayloadHash"] == "a" * 64
    assert result["x_SourceIngestionRunId"] == "bronze-run-1"
    assert result["x_SourcePageNumber"] == 1
    assert result["x_SourceRecordNumber"] == 7
    assert result["x_SourceApiVersion"] == "bigquery-detailed-v1"
    assert result["x_NormalizationVersion"] == "gcp-focus-silver-v3"
    assert result["ingestion_run_id"] is None

    for field in (
        "BillingPeriodStart",
        "BillingPeriodEnd",
        "ChargePeriodStart",
        "ChargePeriodEnd",
        "x_ExportTime",
        "x_GeneratedAt",
        "x_NormalizedAt",
    ):
        value = result[field]
        assert isinstance(value, datetime)
        assert value.tzinfo is None


def test_transform_without_reference_remains_partial() -> None:
    bronze = dict(_bronze_record())
    bronze["reference_billing_account_name"] = None
    bronze["reference_billing_account_name_source"] = None
    bronze["reference_invoice_issuer_name"] = None
    bronze["reference_invoice_issuer_source"] = None

    result = GcpFocusSilverTransformer().transform([cast(Record, bronze)])[0]

    assert result["BillingAccountName"] is None
    assert result["InvoiceIssuerName"] is None
    assert result["x_FocusConformanceStatus"] == "PARTIAL"


def test_transform_empty_sequence() -> None:
    assert GcpFocusSilverTransformer().transform([]) == []


def test_invalid_payload_json_fails() -> None:
    bronze = dict(_bronze_record())
    bronze["payload"] = "{not-json"

    with pytest.raises(ValueError, match="JSON valide"):
        GcpFocusSilverTransformer().transform([cast(Record, bronze)])


def test_payload_must_be_json_object() -> None:
    bronze = dict(_bronze_record())
    bronze["payload"] = "[]"

    with pytest.raises(TypeError, match="objet JSON"):
        GcpFocusSilverTransformer().transform([cast(Record, bronze)])


def test_source_ingestion_run_id_is_required() -> None:
    bronze = dict(_bronze_record())
    bronze["source_ingestion_run_id"] = None

    with pytest.raises(ValueError, match="source_ingestion_run_id"):
        GcpFocusSilverTransformer().transform([cast(Record, bronze)])
