import re
from datetime import UTC, datetime, timedelta
from pathlib import Path
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.gcp_project_discovery_repository import (
    ComputeProject,
    ProjectDirectory,
)
from finops_batches.providers.gcp.project_discovery import (
    CRM,
    USAGE,
    DiscoverySettings,
    ProjectDiscoveryExtractor,
    ProjectDiscoveryTransformer,
)
from finops_batches.providers.gcp.rest_client import GcpRestClient


def context():
    return BatchExecutionContext(
        "MANUAL", datetime.now(UTC).date() - timedelta(days=1), 1, uuid4()
    )


def project(pid, number, parent):
    return {
        "projectId": pid,
        "name": f"projects/{number}",
        "parent": parent,
        "state": "ACTIVE",
    }


class FakeClient:
    def __init__(self):
        self.data = {
            (f"{CRM}/projects", "organizations/123"): [
                {"projects": [project("root-project", "1", "organizations/123")]}
            ],
            (f"{CRM}/folders", "organizations/123"): [
                {
                    "folders": [
                        {
                            "name": "folders/10",
                            "parent": "organizations/123",
                            "state": "ACTIVE",
                        }
                    ]
                }
            ],
            (f"{CRM}/projects", "folders/10"): [
                {"projects": [project("nested-project", "2", "folders/10")]},
                {"projects": [project("other-project", "3", "folders/10")]},
            ],
            (f"{CRM}/folders", "folders/10"): [{}],
            (f"{USAGE}/projects/1/services", None): [
                {"services": [self.service("compute.googleapis.com")]},
                {"services": [self.service("monitoring.googleapis.com")]},
            ],
            (f"{USAGE}/projects/2/services", None): [
                {
                    "services": [
                        self.service("compute.googleapis.com"),
                        self.service("recommender.googleapis.com"),
                    ]
                }
            ],
            (f"{USAGE}/projects/3/services", None): [{}],
        }

    @staticmethod
    def service(name):
        return {"state": "ENABLED", "config": {"name": name}}

    def pages(self, url, params=None):
        assert params is not None
        yield from self.data[(url, params.get("parent"))]

    def close(self):
        pass


def transformed(client, settings):
    ctx = context()
    rows = ProjectDiscoveryTransformer().transform(
        ProjectDiscoveryExtractor(client, settings).extract(ctx)
    )
    for row in rows:
        row["ingestion_run_id"] = str(ctx.logical_run_id)
    return rows


@pytest.fixture
def directory(tmp_path):
    # Equivalent SQLite schema derived from the actual DDL. MariaDB locking is not emulated.
    url = f"sqlite:///{tmp_path / 'directory.db'}"
    ddl = (Path(__file__).parents[1] / "ddl/051_gcp_project_discovery.sql").read_text()
    ddl = re.sub(r"--[^\n]*", "", ddl)
    ddl = re.sub(
        r" CHARACTER SET ascii| ENGINE=InnoDB(?: DEFAULT CHARSET=utf8mb4)?", "", ddl
    )
    ddl = re.sub(r",\s*(?:UNIQUE )?KEY \w+\([^)]*\)", "", ddl)
    ddl = re.sub(r"DATETIME\(6\)", "DATETIME", ddl)
    engine = create_engine(url)
    with engine.begin() as conn:
        for sql in ddl.split(";"):
            if sql.strip():
                conn.execute(text(sql))
    value = ProjectDirectory(url)
    yield value
    value.close()
    engine.dispose()


def test_discovery_publication_and_new_project(directory):
    settings = DiscoverySettings(organization_id="123")
    client = FakeClient()
    rows = transformed(client, settings)
    assert directory.load(rows) > 0
    assert directory.compute_projects(settings) == (
        ComputeProject("nested-project", False, True),
        ComputeProject("root-project", True, False),
    )
    # Project removed from observed hierarchy; new project added without env changes.
    client.data[(f"{CRM}/projects", "folders/10")] = [
        {"projects": [project("new-project", "4", "folders/10")]}
    ]
    client.data[(f"{USAGE}/projects/4/services", None)] = [
        {"services": [client.service("compute.googleapis.com")]}
    ]
    directory.load(transformed(client, settings))
    assert directory.compute_projects(settings) == (
        ComputeProject("new-project", False, False),
        ComputeProject("root-project", True, False),
    )
    with directory.engine.connect() as conn:
        assert (
            conn.execute(
                text(
                    "SELECT is_present FROM finops_gcp_project_silver WHERE project_number='2'"
                )
            ).scalar()
            == 0
        )
        assert (
            conn.execute(
                text(
                    "SELECT COUNT(*) FROM finops_gcp_project_service_silver WHERE project_number='2'"
                )
            ).scalar()
            == 0
        )


def test_scope_and_stale_configuration(directory):
    settings = DiscoverySettings(
        organization_id="123",
        mode="FOLDER",
        folder_ids="10",
        exclude_ids="other-project",
    )
    directory.load(transformed(FakeClient(), settings))
    assert directory.compute_projects(settings) == (
        ComputeProject("nested-project", False, True),
    )
    with pytest.raises(ValueError, match="DISCOVERY_STALE"):
        directory.compute_projects(DiscoverySettings(organization_id="123"))


def test_stale_or_absent_directory(directory):
    settings = DiscoverySettings(organization_id="123")
    with pytest.raises(ValueError, match="DISCOVERY_STALE"):
        directory.compute_projects(settings)
    directory.load(transformed(FakeClient(), settings))
    with directory.engine.begin() as conn:
        conn.execute(
            text(
                "UPDATE finops_gcp_project_discovery_status SET collected_at='2000-01-01 00:00:00'"
            )
        )
    with pytest.raises(ValueError, match="DISCOVERY_STALE"):
        directory.compute_projects(settings)


def test_failed_discovery_does_not_publish(directory):
    settings = DiscoverySettings(organization_id="123")
    client = FakeClient()
    directory.load(transformed(client, settings))
    before = directory.compute_projects(settings)
    del client.data[(f"{USAGE}/projects/2/services", None)]
    with pytest.raises(KeyError):
        transformed(client, settings)
    assert directory.compute_projects(settings) == before
    with pytest.raises(ValueError, match="COMPLETE_MARKER_REQUIRED"):
        directory.load([])


def test_explicit_scope_and_unknown_project(directory):
    settings = DiscoverySettings(
        organization_id="123", mode="EXPLICIT", project_ids="root-project"
    )
    directory.load(transformed(FakeClient(), settings))
    assert directory.compute_projects(settings) == (
        ComputeProject("root-project", True, False),
    )
    with pytest.raises(ValueError, match="UNKNOWN_PROJECT"):
        transformed(
            FakeClient(),
            DiscoverySettings(
                organization_id="123", mode="EXPLICIT", project_ids="missing-project"
            ),
        )


def test_empty_discovery_is_valid(directory):
    client = FakeClient()
    client.data[(f"{CRM}/projects", "organizations/123")] = [{}]
    client.data[(f"{CRM}/folders", "organizations/123")] = [{}]
    settings = DiscoverySettings(organization_id="123")
    assert directory.load(transformed(client, settings)) == 0
    assert directory.compute_projects(settings) == ()


def test_pagination_and_repeated_token():
    session = Mock()
    one, two = Mock(), Mock()
    one.json.return_value = {"nextPageToken": "next"}
    two.json.return_value = {"projects": []}
    session.get.side_effect = [one, two]
    assert list(
        GcpRestClient(session).pages("url", {"parent": "organizations/123"})
    ) == [one.json.return_value, two.json.return_value]
    assert session.get.call_args.kwargs["params"]["pageToken"] == "next"
    session.get.side_effect = [one, one]
    with pytest.raises(ValueError, match="INVALID_PAGINATION_TOKEN"):
        list(GcpRestClient(session).pages("url"))


def test_loader_failure_rolls_back_directory_and_marker(directory):
    from sqlalchemy.exc import IntegrityError

    settings = DiscoverySettings(organization_id="123")
    client = FakeClient()
    directory.load(transformed(client, settings))
    before = directory.compute_projects(settings)
    rows = transformed(client, settings)
    service = next(row for row in rows if row["_kind"] == "service")
    rows.append(dict(service))
    with pytest.raises(IntegrityError):
        directory.load(rows)
    assert directory.compute_projects(settings) == before


def test_previous_day_rejected_even_within_age_limit(directory):
    settings = DiscoverySettings(organization_id="123", max_age_hours=48)
    directory.load(transformed(FakeClient(), settings))
    yesterday = datetime.now(UTC).replace(tzinfo=None) - timedelta(days=1)
    with directory.engine.begin() as conn:
        conn.execute(directory.tables["status"].update().values(collected_at=yesterday))
    with pytest.raises(ValueError, match="DISCOVERY_STALE"):
        directory.compute_projects(settings)
