"""
Secure keystore for persisting keypairs to disk.
"""

from __future__ import annotations

import json
import os
from datetime import datetime, timezone

from broker_auth.keypair import load_private_key, serialize_private_key


class KeyStore:
    """Save/load keypair to JSON file."""

    def __init__(self, path):
        self.path = path

    def save(self, private_key, kid, broker_url, public_jwk):
        """Save keypair data to JSON file."""
        data = {
            "private_key_pem": serialize_private_key(private_key),
            "kid": kid,
            "broker_url": broker_url,
            "public_jwk": public_jwk,
            "enrolled_at": datetime.now(timezone.utc).isoformat(),
        }
        with open(self.path, "w") as f:
            json.dump(data, f, indent=2)

    def load(self):
        """Load keypair data from JSON file. Returns dict or None."""
        if not os.path.exists(self.path):
            return None
        with open(self.path) as f:
            data = json.load(f)
        data["private_key"] = load_private_key(data["private_key_pem"])
        return data

    def exists(self):
        """Check if keystore file exists."""
        return os.path.exists(self.path)
