"""RBS REGAL — Unified Storage Dashboard.

Aggregates stats from every storage subsystem so the user can see at a glance:
  * Local Mongo: total records, DB size estimate
  * Backups: how many snapshots, latest, total compressed size
  * Google Drive: connection state, sync direction, last push timestamp
  * Pending sync queue: how many offline mutations awaiting upload
  * Last-seen timestamps for backup + sync
"""
from __future__ import annotations

from datetime import datetime, timezone
from fastapi import APIRouter, Depends, Request
from auth import get_current_user

router = APIRouter(prefix="/api/storage", tags=["storage"])


def _now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


@router.get("/dashboard")
async def storage_dashboard(request: Request, user=Depends(get_current_user)):
    db = request.app.state.db
    collections = await db.list_collection_names()

    # Latest backup
    latest_backup = await db.backups.find_one({}, sort=[("created_at", -1)])
    backup_count = await db.backups.count_documents({})
    total_backup_bytes = 0
    if backup_count > 0:
        async for d in db.backups.find({}, {"size_bytes": 1}):
            total_backup_bytes += int(d.get("size_bytes", 0) or 0)

    # Drive
    drive = await db.drive_settings.find_one({"_id": "active"}) if "drive_settings" in collections else None
    drive_connected = bool(drive and drive.get("access_token"))

    # Sync queue (offline pending uploads)
    sync_pending = await db.sync_queue.count_documents({}) if "sync_queue" in collections else 0

    # MongoDB stats — approximate dataSize
    try:
        stats = await db.command("dbStats", scale=1)
        data_size_mb = round(float(stats.get("dataSize", 0)) / 1_048_576, 2)
        storage_size_mb = round(float(stats.get("storageSize", 0)) / 1_048_576, 2)
        objects_count = int(stats.get("objects", 0))
    except Exception:
        data_size_mb = storage_size_mb = objects_count = 0

    # Drive backups count (best-effort, just read what we have stored locally)
    drive_backups_count = await db.drive_backups.count_documents({}) if "drive_backups" in collections else 0

    # Last successful sync (best-effort: last backup timestamp)
    last_sync_at = (latest_backup or {}).get("created_at", "")

    return {
        "local": {
            "objects_count": objects_count,
            "data_size_mb": data_size_mb,
            "storage_size_mb": storage_size_mb,
            "collections": len(collections),
        },
        "backups": {
            "count": backup_count,
            "latest_at": (latest_backup or {}).get("created_at", ""),
            "latest_label": (latest_backup or {}).get("label", ""),
            "total_size_mb": round(total_backup_bytes / 1_048_576, 2),
            "drive_synced_count": drive_backups_count,
        },
        "drive": {
            "connected": drive_connected,
            "account_email": (drive or {}).get("account_email", ""),
            "auto_sync": (drive or {}).get("auto_sync", False),
            "last_push_at": (drive or {}).get("last_push_at", ""),
        },
        "sync": {
            "pending_uploads": sync_pending,
            "last_sync_at": last_sync_at,
        },
        "fetched_at": _now_iso(),
    }
