"""Founder RSA key verification for dispatch authorization (Law 0.4)."""
from __future__ import annotations

import json
from pathlib import Path

from pulse.core.paths import get_root_dir

ROOT_DIR = get_root_dir()
AUTH_FILE = ROOT_DIR / "Corpus_Callosum" / "authorized_humans.json"


def verify_founder_key(key_path: str) -> bool:
    """Verify RSA private key matches an authorized founder.

    Loads the private key, extracts its public key, and compares
    against the whitelist in authorized_humans.json.
    """
    key_file = Path(key_path)
    if not key_file.exists():
        print(f"[RELAY] Key file not found: {key_path}")
        return False
    try:
        from cryptography.hazmat.primitives import serialization

        private_key = serialization.load_pem_private_key(
            key_file.read_bytes(), password=None,
        )
        pub_pem = private_key.public_key().public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.SubjectPublicKeyInfo,
        ).decode()

        if not AUTH_FILE.exists():
            print("[RELAY] authorized_humans.json not found — cannot verify founder.")
            return False

        authorized = json.loads(AUTH_FILE.read_text(encoding="utf-8"))
        entries = authorized.values() if isinstance(authorized, dict) else authorized
        for entry in entries:
            if not isinstance(entry, dict):
                continue
            if entry.get("public_key", "").strip() == pub_pem.strip():
                print(f"[RELAY] Founder verified: {entry.get('role', 'FOUNDER')}")
                return True

        print("[RELAY] Key not found in authorized_humans.json.")
        return False
    except ImportError:
        print("[RELAY] cryptography package not installed — cannot verify RSA key.")
        return False
    except Exception as e:
        print(f"[RELAY] Key verification failed: {e}")
        return False
