import tempfile
from pathlib import Path

import click

from axtended_key.models.certificate_metadata import CertificateMetadata
from axtended_key.models.certificate_paths import CertificatePaths
from axtended_key.services.certificate_manager import CertificateManager
from axtended_key.services.keychain_manager import KeychainManager
from axtended_key.utils.logger import logger
from axtended_key.utils.openssl_verification import validate_openssl_version


@click.group()
@click.option("--verbose", is_flag=True, help="Enable verbose log output")
@click.pass_context
def main(ctx, verbose):
    """AXtendedKey CLI Group"""

    logger.set_verbose(verbose)


def validate_openssl():
    """Validate OpenSSL v3 installation."""
    try:
        validate_openssl_version()
    except Exception as e:
        print("Validation of OpenSSL v3 failed, is it installed?")
        print(e)


@main.command()
def generate():
    """Generate a certificate and import into the macOS keychain"""

    # Validate dependencies before run
    validate_openssl()

    # 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
        for file in tmp_dir.iterdir():
            file.unlink()
        tmp_dir.rmdir()


if __name__ == "__main__":
    main()
