from datetime import UTC, datetime, timedelta
from unittest.mock import Mock
from uuid import uuid4

import pytest
from sqlalchemy.exc import NoSuchTableError

from finops_batches.domain.models import BatchExecutionContext
from finops_batches.infrastructure.compute_rightsizing_loader import (
    ComputeRightsizingLoader,
)
from finops_batches.infrastructure.gcp_project_discovery_repository import (
    ComputeProject,
    ProjectDirectory,
)
from finops_batches.providers.gcp.project_discovery import DiscoverySettings
from finops_batches.providers.gcp.rightsizing_etl import (
    RightsizingExtractor,
    RightsizingTransformer,
)


@pytest.mark.parametrize(
    ("kwargs", "message"),
    [
        ({"organization_id": "invalid"}, "GCP_ORGANIZATION_ID"),
        ({"organization_id": "123", "mode": "FOLDER"}, "GCP_FOLDER_IDS"),
        (
            {"organization_id": "123", "mode": "FOLDER", "folder_ids": "bad"},
            "GCP_FOLDER_IDS",
        ),
        ({"organization_id": "123", "mode": "EXPLICIT"}, "GCP_PROJECT_IDS"),
    ],
)
def test_invalid_discovery_scope(kwargs, message):
    with pytest.raises(ValueError, match=message):
        DiscoverySettings(_env_file=None, **kwargs).validate_scope()


@pytest.mark.parametrize("factory", [ComputeRightsizingLoader, ProjectDirectory])
def test_missing_database_schema(factory):
    with pytest.raises(NoSuchTableError):
        factory(database_url="sqlite://")


def test_metrics_etl_preserves_coverage_and_lineage_fields():
    day = datetime.now(UTC).date() - timedelta(days=2)
    context = BatchExecutionContext("MANUAL", day, 1, uuid4())
    collector = Mock()
    collector.metrics.return_value = iter(
        [
            {
                "zone": "z",
                "instance_id": "123",
                "metric": "cpu",
                "unit": "ratio",
                "count": 2,
                "expected": 1440,
                "series_count": 1,
                "incomplete_slots": 0,
                "sum": 0.5,
                "min": 0.2,
                "max": 0.3,
                "histogram": {21: 1, 31: 1},
            }
        ]
    )
    directory = Mock()
    directory.compute_projects.return_value = (ComputeProject("p", True, True),)
    extractor = RightsizingExtractor(
        collector, directory, DiscoverySettings(organization_id="123")
    )
    rows = RightsizingTransformer().transform(extractor.extract(context))
    assert len(rows) == 2
    marker, metric = rows
    assert marker["collection_status"] == "SUCCESS"
    assert metric["usage_day"] == day
    assert metric["project_id"] == "p"
    assert metric["sample_count"] == 2
    assert metric["expected_count"] == 1440
    assert metric["histogram_version"] == 1
    assert metric["histogram"] == '{"21":1,"31":1}'
    assert metric["ingestion_run_id"] is None  # Set by DataBatchJob.
    collector.snapshot.assert_not_called()
    extractor.close()
    collector.close.assert_called_once_with()
    directory.close.assert_called_once_with()


def test_extractor_closes_directory_on_collector_close_failure():
    collector = Mock()
    collector.close.side_effect = RuntimeError("close failed")
    directory = Mock()
    extractor = RightsizingExtractor(
        collector, directory, DiscoverySettings(organization_id="123")
    )
    with pytest.raises(RuntimeError, match="close failed"):
        extractor.close()
    directory.close.assert_called_once_with()
