"""Optiwise ETL envelope for compact Compute Engine observations."""

from __future__ import annotations

from collections.abc import Sequence
from datetime import UTC, datetime, timedelta
from typing import cast

from finops_batches.domain.models import BatchExecutionContext, Record
from finops_batches.infrastructure.gcp_project_discovery_repository import (
    ProjectDirectory,
)
from finops_batches.providers.gcp.compute_rightsizing import Collector
from finops_batches.providers.gcp.project_discovery import DiscoverySettings
from finops_batches.providers.gcp.rest_client import canonical, digest


class RightsizingExtractor:
    def __init__(
        self,
        collector: Collector,
        directory: ProjectDirectory,
        settings: DiscoverySettings,
    ) -> None:
        self.collector = collector
        self.directory = directory
        self.settings = settings

    def extract(self, context: BatchExecutionContext) -> list[Record]:
        now = datetime.now(UTC)
        day = context.business_date
        if not now.date() - timedelta(days=120) <= day < now.date():
            raise ValueError("RIGHTSIZING_DATE_OUTSIDE_RETENTION")
        stamp = now.replace(tzinfo=None)
        records: list[Record] = []
        projects = self.directory.compute_projects(self.settings)
        if not projects:
            return [{"_kind": "scope_empty", "ingestion_run_id": None}]
        for project in projects:
            pid = project.project_id
            for kind, data_day, enabled in (
                ("metrics", day, project.monitoring_enabled),
                ("snapshot", now.date(), True),
            ):
                if kind == "snapshot" and day != now.date() - timedelta(days=1):
                    continue
                status = "SUCCESS"
                detail = None
                if not enabled:
                    status, detail = "API_DISABLED", "monitoring.googleapis.com"
                elif kind == "snapshot" and not project.recommender_enabled:
                    status, detail = "PARTIAL", "recommender.googleapis.com"
                records.append(
                    {
                        "_kind": "marker",
                        "collection_kind": kind,
                        "project_id": pid,
                        "data_day": data_day,
                        "collected_at": stamp,
                        "ingestion_run_id": None,
                        "collection_status": status,
                        "status_detail": detail,
                    }
                )
                if not enabled:
                    continue
                source = (
                    self.collector.metrics(pid, day)
                    if kind == "metrics"
                    else self.collector.snapshot(
                        pid, include_recommendations=project.recommender_enabled
                    )
                )
                for row in source:
                    records.append(
                        {
                            "_kind": kind,
                            "project_id": pid,
                            "data_day": data_day,
                            "collected_at": stamp,
                            "source": row,
                            "ingestion_run_id": None,
                        }
                    )
        return records

    def close(self) -> None:
        try:
            self.collector.close()
        finally:
            self.directory.close()


class RightsizingTransformer:
    def transform(self, records: Sequence[Record]) -> list[Record]:
        result: list[Record] = []
        for record in records:
            kind = record["_kind"]
            if kind in ("marker", "scope_empty"):
                result.append(dict(record))
                continue
            row = cast(dict[str, object], record["source"])
            common: Record = {
                "_kind": kind,
                "project_id": record["project_id"],
                "ingestion_run_id": None,
            }
            if kind == "snapshot":
                common.update(
                    snapshot_day=record["data_day"],
                    observed_at=record["collected_at"],
                    kind=row["kind"],
                    location=row["zone"],
                    resource_key=row["key"],
                    payload=canonical(row["payload"]),
                    payload_hash=digest(row["payload"]),
                )
            elif kind == "metrics":
                common.update(
                    usage_day=record["data_day"],
                    zone=row["zone"],
                    instance_id=row["instance_id"],
                    metric=row["metric"],
                    unit=row["unit"],
                    sample_count=row["count"],
                    expected_count=row["expected"],
                    series_count=row["series_count"],
                    incomplete_slots=row["incomplete_slots"],
                    sample_sum=row["sum"],
                    sample_min=row["min"],
                    sample_max=row["max"],
                    histogram=canonical(row["histogram"]),
                    histogram_version=1,
                    collected_at=record["collected_at"],
                )
            else:
                raise ValueError("RIGHTSIZING_UNKNOWN_RECORD")
            result.append(common)
        return result
