"""Generate Hayva encryption and asymmetric Computer capability keys."""

import argparse
import base64
import os
from pathlib import Path

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey


def encoded(value: bytes) -> str:
    return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=")


def write_exclusive(path: Path, value: str) -> None:
    path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
        handle.write(value + "\n")


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Generate protected local secret files; refuses to overwrite existing keys."
    )
    parser.add_argument("--secrets-root", type=Path, default=Path("secrets"))
    args = parser.parse_args()
    targets = (
        args.secrets_root / "internal" / "app-secret",
        args.secrets_root / "encryption" / "data-encryption-key",
        args.secrets_root / "internal" / "computer-capability-private-key",
        args.secrets_root / "internal" / "computer-capability-public-key",
        args.secrets_root / "internal" / "ai-service-token",
        args.secrets_root / "internal" / "computer-service-token",
        args.secrets_root / "bootstrap" / "owner_token",
    )
    existing = [str(path) for path in targets if path.exists()]
    if existing:
        parser.error("Refusing to overwrite existing security files: " + ", ".join(existing))
    private = Ed25519PrivateKey.generate()
    private_raw = private.private_bytes(
        serialization.Encoding.Raw,
        serialization.PrivateFormat.Raw,
        serialization.NoEncryption(),
    )
    public_raw = private.public_key().public_bytes(
        serialization.Encoding.Raw, serialization.PublicFormat.Raw
    )
    write_exclusive(targets[0], encoded(os.urandom(32)))
    write_exclusive(targets[1], encoded(os.urandom(32)))
    write_exclusive(
        targets[2],
        encoded(private_raw),
    )
    write_exclusive(
        targets[3],
        encoded(public_raw),
    )
    write_exclusive(targets[4], encoded(os.urandom(32)))
    write_exclusive(targets[5], encoded(os.urandom(32)))
    write_exclusive(targets[6], encoded(os.urandom(32)))
    print(f"Security keys created under {args.secrets_root.resolve()}")


if __name__ == "__main__":
    main()
