from pathlib import Path
import tempfile
from models.certificate_metadata import CertificateMetadata
from models.certificate_paths import CertificatePaths
from services.certificate_manager import CertificateManager
from services.keychain_manager import KeychainManager


def main():
    # Step 1: Create a temporary directory for certificate operations
    tmp_dir = Path(tempfile.mkdtemp())
    paths = CertificatePaths.from_directory(tmp_dir)
    metadata = CertificateMetadata(common_name="AXtendedKey Autogenerated | AX Root Trust Certificate")

    try:
        # Step 2: Generate and package the certificate
        cert_manager = CertificateManager(metadata=metadata, paths=paths)
        cert_manager.run_all()

        # Step 3: Import the certificate into the macOS keychain and set trust
        keychain_manager = KeychainManager(paths=paths, password=metadata.password)
        keychain_manager.run_all()

    finally:
        # Step 4: Cleanup the temporary directory
        print(f"Cleaning up temporary files in {tmp_dir}")
        for file in tmp_dir.iterdir():
            file.unlink()
        tmp_dir.rmdir()


if __name__ == "__main__":
    main()
