"""
4Alarm - Tuya API client per-tenant
Each tenant has its own Tuya credentials stored in the `tenants` collection.
"""
from tuya_connector import TuyaOpenAPI
import time

# Per-tenant Tuya connections cache
_tuya_connections = {}  # tenant_id -> {api, connected_at}


def get_tuya_api(tenant: dict) -> TuyaOpenAPI:
    """Get or create a Tuya API connection for a specific tenant."""
    tenant_id = tenant.get("id", "")
    endpoint = tenant.get("tuya_endpoint", "https://openapi.tuyaus.com")
    access_id = tenant.get("tuya_access_id", "")
    access_secret = tenant.get("tuya_access_secret", "")

    if not access_id or not access_secret:
        return None

    now = time.time()
    cached = _tuya_connections.get(tenant_id)
    if cached and (now - cached["connected_at"]) < 3600:
        return cached["api"]

    api = TuyaOpenAPI(endpoint, access_id, access_secret)
    resp = api.connect()
    if resp.get("success"):
        _tuya_connections[tenant_id] = {"api": api, "connected_at": now}
        return api
    return None


def tuya_request(tenant: dict, method: str, path: str, body=None):
    """Make a Tuya API request for a specific tenant with retry."""
    for attempt in range(2):
        try:
            api = get_tuya_api(tenant)
            if not api:
                return {"success": False, "msg": "Tuya no configurado para este tenant"}
            if method == "get":
                resp = api.get(path) if body is None else api.get(path, body)
            else:
                resp = api.post(path, body)

            if not resp.get("success") and resp.get("code") == 1110:
                if attempt == 0:
                    time.sleep(2)
                    continue
            if not resp.get("success") and resp.get("code") in (1010, 1004):
                _tuya_connections.pop(tenant.get("id", ""), None)
                if attempt == 0:
                    continue
            return resp
        except Exception as e:
            _tuya_connections.pop(tenant.get("id", ""), None)
            if attempt == 0:
                time.sleep(1)
                continue
            return {"success": False, "msg": str(e)}
    return {"success": False, "msg": "Max retries"}
