import os
import sys
import requests
import zipfile
from github.github_apis import create_git_headers

git_url = "https://api.github.com/repos"
headers = create_git_headers()

# Download artifact by name from given repository and workflow run id and extract to out dir
def download_artifact(repo_name, run_id, artifact_name):
    output_path = "artifact.zip"
    response = requests.get(f'{git_url}/{repo_name}/actions/runs/{run_id}/artifacts', headers=headers)
    if response.status_code == 200:
        artifacts = response.json().get('artifacts', [])
        for artifact in artifacts:
            if artifact["name"] == artifact_name:
                download_url = artifact["archive_download_url"]
                download_response = requests.get(download_url, headers=headers)
                with open(output_path, "wb") as f:
                    f.write(download_response.content)
                print(f"Downloaded artifact as {output_path}")
                os.makedirs("out", exist_ok=True)
                with zipfile.ZipFile(output_path, 'r') as zip_ref:
                    zip_ref.extractall("out")
                return
        print(f"No artifact named {artifact_name} found.")
    else:
        print("Error fetching artifacts.")
        print(response.status_code, response.text)
        exit(1)

if __name__ == "__main__":
    repo_name = sys.argv[1].replace("repo_name=", "", 1)
    run_id = sys.argv[2].replace("run_id=", "", 1)
    artifact_name = sys.argv[3].replace("artifact_name=", "", 1)

    download_artifact(repo_name, run_id, artifact_name)
