from __future__ import annotations

from typing import TYPE_CHECKING, Optional

from mockmesh.interceptors.common import parse_json_body

if TYPE_CHECKING:
    from mockmesh.storage.manager import StorageManager


def handle_ssm(sm: "StorageManager", req: dict, operation: str) -> Optional[dict]:
    bd = parse_json_body(req)
    if operation == "PutParameter":
        sm.ssm_put(name=bd.get("Name", "unknown"), value=bd.get("Value", ""),
                   param_type=bd.get("Type", "String"))
        return {"Version": 1, "Tier": "Standard"}
    if operation == "GetParameter":
        item = sm.ssm_get(bd.get("Name", ""))
        return {"Parameter": item} if item else None
    if operation == "GetParametersByPath":
        return {"Parameters": sm.ssm_get_by_path(bd.get("Path", "/")), "NextToken": None}
    return None


def handle_secretsmanager(sm: "StorageManager", req: dict, operation: str) -> Optional[dict]:
    bd = parse_json_body(req)
    if operation in ("CreateSecret", "PutSecretValue"):
        name  = bd.get("Name") or bd.get("SecretId", "unknown")
        entry = sm.secret_put(name, bd.get("SecretString", "{}"))
        return {"ARN": entry["ARN"], "Name": entry["Name"], "VersionId": entry["VersionId"]}
    if operation == "GetSecretValue":
        item = sm.secret_get(bd.get("SecretId", ""))
        return item if item else None
    return None


def handle_elasticache(sm: "StorageManager", req: dict, operation: str) -> Optional[dict]:
    bd = parse_json_body(req)
    if operation == "CreateCacheCluster":
        cid   = bd.get("CacheClusterId", "mock-cache")
        attrs = {
            "CacheClusterId":     cid,
            "CacheClusterStatus": "available",
            "Engine":             bd.get("Engine", "redis"),
            "EngineVersion":      bd.get("EngineVersion", "7.0.12"),
            "CacheNodeType":      bd.get("CacheNodeType", "cache.t3.micro"),
            "NumCacheNodes":      bd.get("NumCacheNodes", 1),
        }
        sm.cache_cluster_put(cid, attrs)
        return {"CacheCluster": attrs}
    if operation == "DescribeCacheClusters":
        cid      = bd.get("CacheClusterId")
        clusters = [sm.cache_cluster_get(cid)] if cid else sm.cache_cluster_list()
        return {"CacheClusters": [c for c in clusters if c]}
    if operation == "CreateReplicationGroup":
        rg_id = bd.get("ReplicationGroupId", "mock-rg")
        attrs = {
            "ReplicationGroupId": rg_id,
            "Status":             "available",
            "Description":        bd.get("ReplicationGroupDescription", ""),
            "AutomaticFailover":  "enabled" if bd.get("AutomaticFailoverEnabled") else "disabled",
            "MultiAZ":            "enabled" if bd.get("MultiAZEnabled") else "disabled",
            "CacheNodeType":      bd.get("CacheNodeType", "cache.t3.small"),
        }
        sm.cache_rg_put(rg_id, attrs)
        return {"ReplicationGroup": attrs}
    if operation == "DescribeReplicationGroups":
        rg_id  = bd.get("ReplicationGroupId")
        groups = [sm.cache_rg_get(rg_id)] if rg_id else sm.cache_rg_list()
        return {"ReplicationGroups": [g for g in groups if g]}
    return None
