from argparse import ArgumentParser
from aleph_secrets_manager.src.gh_secrets_adaptor import GitHubSecretsManager
import logging
import os


def main():
    parser = ArgumentParser()
    parser.add_argument("-o", "--org", help="GitHub organization name", required=True)
    parser.add_argument("-r", "--repo", help="GitHub repository name", required=True)
    subparsers = parser.add_subparsers(dest="command")

    # List all secrets
    subparsers.add_parser("list", help="List all secret names in the repository")

    # Write a secret
    write_parser = subparsers.add_parser("write", help="Write a secret to the repository")
    write_parser.add_argument("-f", "--file-path", help="File path to .env", required=True)

    # Delete a secret
    delete_parser = subparsers.add_parser("delete", help="Delete a secret from the repository")
    delete_parser.add_argument("-k", "--key", required=True, help="Secret key name to delete")

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

    token = os.getenv('GH_AUTH_TOKEN')
    if not token:
        raise Exception("❌ Token has not been set. Please set the environment variable `GH_AUTH_TOKEN` with your personal access token.")
    secrets_manager = GitHubSecretsManager(org=args.org, repo=args.repo, auth_token=token)

    if args.command == "list":
        secrets = secrets_manager.list_all_secrets()
        print(f"Repository secrets: {secrets}")
    elif args.command == "write":
        secrets_manager.upload_from_env_file(env_path=args.file_path)
        print(f"✅ Uploaded secrets from {str(args.file_path)} to {args.org}/{args.repo}")
    elif args.command == "delete":
        secrets_manager.delete_secret(args.key)
        print(f"✅ Deleted secret {args.key} from {args.org}/{args.repo}")
    else:
        parser.print_help()

if __name__ == "__main__":
    main()
