from __future__ import annotations
from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
    from mockmesh.storage.manager import StorageManager

_COLLECTION = "gcp_secrets"


def handle_secret_manager(
    sm: "StorageManager",
    project: str,
    secret_id: str,
    operation: str,
    body: dict,
    tpl: dict,
) -> Optional[dict]:
    full_name = f"projects/{project}/secrets/{secret_id}"

    # ── Secret CRUD ───────────────────────────────────────────────────
    if operation == "create":
        sm.nosql.put(_COLLECTION, secret_id, {
            "name":        full_name,
            "replication": body.get("replication", {"automatic": {}}),
            "versions":    {},
        })
        resp = dict(tpl.get("projects_secrets_create", {}))
        resp["name"] = full_name
        return resp

    if operation == "get":
        item = sm.nosql.get(_COLLECTION, secret_id)
        resp = dict(tpl.get("projects_secrets_get", {}))
        resp["name"] = full_name
        if item:
            resp.update(item)
        return resp

    if operation == "delete":
        sm.nosql.delete(_COLLECTION, secret_id)
        return {}

    if operation == "list":
        items = sm.nosql.list(_COLLECTION)
        resp  = dict(tpl.get("projects_secrets_list", {"secrets": [], "totalSize": 0}))
        resp["secrets"] = [{"name": r["value"].get("name", r["key"])} for r in items]
        resp["totalSize"] = len(resp["secrets"])
        return resp

    # ── Version operations ────────────────────────────────────────────
    if operation == "addVersion":
        secret = sm.nosql.get(_COLLECTION, secret_id) or {
            "name": full_name, "replication": {"automatic": {}}, "versions": {}
        }
        versions = secret.get("versions", {})
        ver_num  = str(len(versions) + 1)
        raw_data = body.get("payload", {}).get("data", "")
        versions[ver_num] = {
            "name":       f"{full_name}/versions/{ver_num}",
            "state":      "ENABLED",
            "createTime": "2024-01-01T00:00:00.000000Z",
            "data":       raw_data,
        }
        secret["versions"] = versions
        sm.nosql.put(_COLLECTION, secret_id, secret)
        resp = dict(tpl.get("projects_secrets_versions_add", {}))
        resp["name"] = f"{full_name}/versions/{ver_num}"
        return resp

    if operation in ("accessVersion", "access", "getLatestVersion"):
        secret   = sm.nosql.get(_COLLECTION, secret_id) or {}
        versions = secret.get("versions", {})
        if versions:
            latest = versions[max(versions.keys(), key=int)]
            resp   = dict(tpl.get("projects_secrets_versions_access", {}))
            resp["name"]            = latest["name"]
            resp["payload"]         = {"data": latest.get("data", ""), "dataCrc32c": "mock-crc"}
            return resp
        return dict(tpl.get("projects_secrets_versions_access", {}))

    if operation == "getVersion":
        resp = dict(tpl.get("projects_secrets_versions_get", {}))
        resp["name"] = f"{full_name}/versions/1"
        return resp

    if operation == "listVersions":
        secret   = sm.nosql.get(_COLLECTION, secret_id) or {}
        versions = secret.get("versions", {})
        resp     = dict(tpl.get("projects_secrets_versions_list", {"versions": [], "totalSize": 0}))
        resp["versions"]  = [{"name": v["name"], "state": v.get("state", "ENABLED")}
                              for v in versions.values()]
        resp["totalSize"] = len(resp["versions"])
        return resp

    if operation == "disableVersion":
        return dict(tpl.get("projects_secrets_versions_disable", {}))

    if operation == "destroyVersion":
        return dict(tpl.get("projects_secrets_versions_destroy", {}))

    return None
