import argparse

import gitlab
import yaml


# Function to fetch all CI/CD variables from a GitLab project
def fetch_variables(project):
    p_variables = list(project.variables.list(iterator=True))
    variables = [var.asdict() for var in p_variables]

    return variables


def fetch_sched_variables(sched_pipeline):
    variables = sched_pipeline.attributes["variables"]
    return variables


# Main function to load the config and fetch variables
def main():
    # Setup argument parser
    parser = argparse.ArgumentParser(description="GitLab CI/CD Variable reader")
    parser.add_argument(
        "--config_file",
        type=str,
        default="gitlab.ini",
        required=True,
        help="Path to the configuration file (default: gitlab.ini)",
    )
    parser.add_argument(
        "--var_file",
        type=str,
        default="ci-variables.yaml",
        help="Path to the CI vars file (default: ci-variables.yaml)",
    )
    parser.add_argument(
        "--project_name",
        type=str,
        required=True,
        help="Gitlab project name with namespace",
    )
    parser.add_argument(
        "--sched_pipeline_id",
        type=int,
        help="Gitlab project scheduled pipeline ID",
    )

    # Parse the arguments
    args = parser.parse_args()

    gl = gitlab.Gitlab.from_config("uabrc", [args.config_file])
    project = gl.projects.get(args.project_name)

    # Fetch project or sched pipeline variables
    if not args.sched_pipeline_id:
        variables = fetch_variables(project)
    else:
        sched_pipeline = project.pipelineschedules.get(args.sched_pipeline_id)
        variables = fetch_sched_variables(sched_pipeline)

    try:
        with open(args.var_file, mode="wt", encoding="utf-8") as file:
            yaml.dump(variables, file, explicit_start=True)
    except FileNotFoundError:
        print(f"Error: Writing File to '{args.var_file}'")
        exit(1)


# Run the main function
if __name__ == "__main__":
    main()