"""GCS findings upload/download helpers.

Manages findings JSON storage in the complyform-prod-findings bucket
with per-customer/project/scan path structure and in-memory caching.
"""

from __future__ import annotations

import json
import logging
import time
from typing import Any

_log = logging.getLogger(__name__)

FINDINGS_BUCKET = "complyform-prod-findings"

_findings_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}
_CACHE_TTL_SECONDS = 300  # 5 minutes


async def upload_findings(
    customer_id: str,
    project_id: str,
    scan_id: str,
    findings: list[dict[str, Any]],
) -> str:
    """Upload findings JSON to GCS. Returns gs:// URI."""
    from google.cloud import storage

    blob_path = f"{customer_id}/{project_id}/{scan_id}.json"
    uri = f"gs://{FINDINGS_BUCKET}/{blob_path}"

    client = storage.Client(project="complyform-prod")
    bucket = client.bucket(FINDINGS_BUCKET)
    blob = bucket.blob(blob_path)
    blob.upload_from_string(
        json.dumps(findings),
        content_type="application/json",
    )

    _log.info("Uploaded findings to %s", uri)
    return uri


async def download_findings(findings_uri: str) -> list[dict[str, Any]]:
    """Download findings JSON from GCS URI. 5-min in-memory cache per URI."""
    now = time.monotonic()

    cached = _findings_cache.get(findings_uri)
    if cached is not None:
        cached_at, cached_data = cached
        if now - cached_at < _CACHE_TTL_SECONDS:
            return cached_data

    from google.cloud import storage

    if not findings_uri.startswith(f"gs://{FINDINGS_BUCKET}/"):
        msg = f"Invalid findings URI: {findings_uri}"
        raise ValueError(msg)

    blob_path = findings_uri[len(f"gs://{FINDINGS_BUCKET}/") :]
    client = storage.Client(project="complyform-prod")
    bucket = client.bucket(FINDINGS_BUCKET)
    blob = bucket.blob(blob_path)
    raw = blob.download_as_text()
    data: list[dict[str, Any]] = json.loads(raw)

    _findings_cache[findings_uri] = (now, data)
    return data
