import os
import logging
from gen3.auth import Gen3Auth
from gen3.submission import Gen3Submission
from typing import Optional, List
from acdc_aws_etl_pipeline.upload.metadata_submitter import (
    create_boto3_session,
    get_gen3_api_key_aws_secret,
    infer_api_endpoint_from_jwt,
    create_gen3_submission_class
)

logger = logging.getLogger(__name__)

def delete_project_metadata(
    import_order_file: str,
    project_id: str,
    aws_secret_name: str,
    aws_profile: Optional[str] = None,
    aws_region: str = "us-east-1",
    exclude_nodes: Optional[List[str]] = None,
    prompt_for_confirmation: bool = True,
):
    """
    Deletes metadata json files from the gen3 api endpoint. Deletion depends on
    a DataImportOrder.txt file, which defines the order of the nodes to be
    deleted.

    Args:
        import_order_file (str): The path to the import order file
        project_id (str): The ID of the project.
        aws_secret_name (str): The name of the AWS secret containing the Gen3
            API key.
        aws_profile (str, optional): AWS profile name.
        aws_region (str, optional): AWS region. Default is "ap-southeast-2".
        exclude_nodes (list): A list of node names to exclude from the
            deletion. Default is ["project", "program", "acknowledgement",
            "publication"].
        prompt_for_confirmation (bool): Whether to prompt for confirmation
            before deletion.

    Returns:
        None
    """

    if aws_region is None:
        aws_region = "ap-southeast-2"
    if aws_profile is None:
        aws_profile = "default"

    if exclude_nodes is None:
        exclude_nodes = [
            "project",
            "program",
            "acknowledgement",
            "publication",
        ]

    def get_import_order(import_order_file):
        try:
            with open(import_order_file, "r", encoding="utf-8") as f:
                import_order = [line.rstrip() for line in f]
                import_order = [
                    node for node in import_order if node not in exclude_nodes
                ]
            return import_order
        except FileNotFoundError:
            logger.error(
                "DataImportOrder.txt not found in %s", import_order_file
            )
            return []

    ordered_import_nodes = get_import_order(import_order_file)

    # AWS and Gen3 Authentication
    session = create_boto3_session(aws_profile)
    api_key_dict = get_gen3_api_key_aws_secret(
        aws_secret_name, aws_region, session
    )
    if api_key_dict is None:
        logger.error("API key not found in AWS secret %s", aws_secret_name)
        return

    sub = create_gen3_submission_class(api_key_dict)

    final_ordered_import_nodes = [
        node for node in ordered_import_nodes if node not in exclude_nodes
    ]
    final_ordered_import_nodes.reverse()  # Reverse the order for deletion

    if prompt_for_confirmation:
        confirm = input(
            "Do you want to delete the metadata? (yes/no): "
        ).strip().lower()
        if confirm != "yes":
            logger.info("Deletion cancelled by user.")
            return

    for node in final_ordered_import_nodes:
        logger.info("[DELETE]  | Project: %-10s | Node: %-12s", project_id, node)
        try:
            sub.delete_nodes("program1", project_id, [node])
            logger.info(
                "\033[92m[SUCCESS]\033[0m | Project: %-10s | Node: %-12s",
                project_id,
                node,
            )
        except Exception as e:
            logger.error(
                "\033[91m[FAILED]\033[0m  | Project: %-10s | Node: %-12s | "
                "Error: %s",
                project_id,
                node,
                e,
            )
