from argparse import ArgumentParser
from pathlib import Path
from aleph_secrets_manager.src.port import Secret
from aleph_secrets_manager.src.azure_keyvault_adaptor import (
    AzureSecretsManager,
    AzureClientFactory,
)
import logging


def main():
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--vault-name",
        help="Name of Azure Key Vault to read/write to.",
        required=True,
    )
    subparsers = parser.add_subparsers(dest="command")

    read_parser = subparsers.add_parser("read", help="Read mode")
    read_parser.add_argument(
        "-f", "--file-path", help="File path to .env", required=True
    )

    write_parser = subparsers.add_parser("write", help="Write mode")
    write_parser.add_argument(
        "-f", "--file-path", help="File path to .env", required=True
    )

    delete_parser = subparsers.add_parser("delete", help="Delete mode")
    delete_parser.add_argument(
        "-k",
        "--keys",
        action="append",
        help="Keys to take action on. ",
    )

    args = parser.parse_args()
    logging.debug(f"⚙ Arguments received: {args}")

    secrets_manager = AzureSecretsManager(AzureClientFactory.create(args.vault_name))
    if args.command == "read":
        secrets_manager.download_all_to_env_file(env_path=Path(args.file_path))
        print(f"✅ Downloaded secrets to {str(args.file_path)}")
    elif args.command == "write":
        secrets_manager.upload_from_env_file(env_path=Path(args.file_path))
        print(f"✅ Uploaded secrets from {str(args.file_path)} to {args.vault_name}")
    elif args.command == "delete":
        for deletion in args.keys:
            secrets_manager.delete_secret(deletion)
        print(f"✅ Deleted secrets {args.keys} from {args.vault_name}")


if __name__ == "__main__":
    main()
