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

import pytest
from sqlalchemy import create_engine, text

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,
)
from finops_batches.providers.gcp.project_discovery import DiscoverySettings
from finops_batches.providers.gcp.rightsizing_etl import (
    RightsizingExtractor,
    RightsizingTransformer,
)


def make_extractor(client, projects=None):
    directory = Mock()
    directory.compute_projects.return_value = (
        (ComputeProject("sample-project", True, True),)
        if projects is None
        else projects
    )
    return RightsizingExtractor(
        client, directory, DiscoverySettings(organization_id="123")
    )


def test_historical_replay_does_not_create_snapshot():
    client = Mock()
    client.metrics.return_value = iter([])
    day = datetime.now(UTC).date() - timedelta(days=10)
    ctx = BatchExecutionContext("BACKFILL", day, 1, uuid4())
    rows = make_extractor(client).extract(ctx)
    assert len(rows) == 1
    assert rows[0]["collection_kind"] == "metrics"
    client.snapshot.assert_not_called()


def test_yesterday_collects_current_inventory():
    client = Mock()
    client.metrics.return_value = iter([])
    client.snapshot.return_value = iter(
        [{"kind": "instance", "zone": "a", "key": "1", "payload": {"id": "1"}}]
    )
    today = datetime.now(UTC).date()
    ctx = BatchExecutionContext("MANUAL", today - timedelta(days=1), 1, uuid4())
    rows = RightsizingTransformer().transform(make_extractor(client).extract(ctx))
    assert rows[-1]["snapshot_day"] == today
    assert rows[-1]["payload"] == '{"id":"1"}'


def test_current_day_rejected():
    client = Mock()
    ctx = BatchExecutionContext("MANUAL", datetime.now(UTC).date(), 1, uuid4())
    with pytest.raises(ValueError, match="OUTSIDE_RETENTION"):
        make_extractor(client).extract(ctx)
    client.metrics.assert_not_called()


def test_scoped_replace_and_empty(tmp_path):
    url = f"sqlite:///{tmp_path / 'test.db'}"
    engine = create_engine(url)
    with engine.begin() as conn:
        conn.execute(
            text(
                "CREATE TABLE finops_gcp_compute_snapshot_bronze (snapshot_day DATE, project_id TEXT, observed_at DATETIME, kind TEXT, location TEXT, resource_key TEXT, payload TEXT, payload_hash TEXT, ingestion_run_id TEXT, PRIMARY KEY(snapshot_day,project_id,kind,location,resource_key))"
            )
        )
        conn.execute(
            text(
                "CREATE TABLE finops_gcp_compute_metric_silver (usage_day DATE, project_id TEXT, zone TEXT, instance_id TEXT, metric TEXT, unit TEXT, sample_count INT, expected_count INT, series_count INT, incomplete_slots INT, sample_sum REAL, sample_min REAL, sample_max REAL, histogram TEXT, histogram_version INT, collected_at DATETIME, ingestion_run_id TEXT, PRIMARY KEY(usage_day,project_id,zone,instance_id,metric))"
            )
        )
        conn.execute(
            text(
                "CREATE TABLE finops_gcp_compute_collection_status (project_id TEXT, data_day DATE, collection_kind TEXT, collected_at DATETIME, row_count INT, ingestion_run_id TEXT, collection_status TEXT, status_detail TEXT, PRIMARY KEY(project_id,data_day,collection_kind))"
            )
        )
    loader = ComputeRightsizingLoader(database_url=url)
    stamp = datetime.now(UTC).replace(tzinfo=None)
    day = stamp.date()
    head = {
        "_kind": "marker",
        "collection_kind": "snapshot",
        "project_id": "p",
        "data_day": day,
        "collected_at": stamp,
        "ingestion_run_id": "run",
    }
    row = {
        "_kind": "snapshot",
        "snapshot_day": day,
        "project_id": "p",
        "observed_at": stamp,
        "kind": "instance",
        "location": "z",
        "resource_key": "1",
        "payload": "{}",
        "payload_hash": "hash",
        "ingestion_run_id": "run",
    }
    assert loader.load([head, row]) == 1
    assert loader.load([head, row]) == 1
    with pytest.raises(ValueError, match="RUN_REQUIRED"):
        loader.load([head, dict(row, ingestion_run_id="bad")])
    with engine.connect() as conn:
        assert (
            conn.execute(
                text("SELECT COUNT(*) FROM finops_gcp_compute_snapshot_bronze")
            ).scalar()
            == 1
        )
    disabled = dict(
        head,
        collection_status="API_DISABLED",
        status_detail="monitoring.googleapis.com",
    )
    assert loader.load([disabled]) == 0
    with engine.connect() as conn:
        assert (
            conn.execute(
                text("SELECT COUNT(*) FROM finops_gcp_compute_snapshot_bronze")
            ).scalar()
            == 1
        )
        assert (
            conn.execute(
                text(
                    "SELECT collection_status FROM finops_gcp_compute_collection_status"
                )
            ).scalar()
            == "API_DISABLED"
        )
    assert loader.load([head]) == 0
    with engine.connect() as conn:
        assert (
            conn.execute(
                text("SELECT COUNT(*) FROM finops_gcp_compute_snapshot_bronze")
            ).scalar()
            == 0
        )
        assert (
            conn.execute(
                text("SELECT row_count FROM finops_gcp_compute_collection_status")
            ).scalar()
            == 0
        )
    loader.close()
    engine.dispose()


def test_missing_apis_are_not_empty_collections():
    client = Mock()
    client.snapshot.return_value = iter([])
    ctx = BatchExecutionContext(
        "MANUAL", datetime.now(UTC).date() - timedelta(days=1), 1, uuid4()
    )
    rows = make_extractor(
        client, (ComputeProject("sample-project", False, False),)
    ).extract(ctx)
    assert [r["collection_status"] for r in rows] == ["API_DISABLED", "PARTIAL"]
    client.metrics.assert_not_called()
    client.snapshot.assert_called_once_with(
        "sample-project", include_recommendations=False
    )


def test_complete_empty_scope():
    client = Mock()
    ctx = BatchExecutionContext(
        "MANUAL", datetime.now(UTC).date() - timedelta(days=1), 1, uuid4()
    )
    rows = make_extractor(client, ()).extract(ctx)
    assert rows == [{"_kind": "scope_empty", "ingestion_run_id": None}]
    client.metrics.assert_not_called()
