import requests
import json
from dotenv import load_dotenv
from os import getenv
import base64

load_dotenv()

# load env vars
REPO_OWNER = getenv("REPO_OWNER")
REPO_NAME = getenv("REPO_NAME")
BASE_BRANCH = getenv("BASE_BRANCH")
GITHUB_TOKEN = getenv("GITHUB_TOKEN")

# GitHub API URL
API_URL = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}"

# Headers for authentication
HEADERS = {
    "Authorization": f"token {GITHUB_TOKEN}",
    "Accept": "application/vnd.github.v3+json",
}


def get_file_sha(file_path):
    url = f"{API_URL}/contents/{file_path}?ref={BASE_BRANCH}"
    response = requests.get(url, headers=HEADERS)

    if response.status_code == 200:
        return response.json()["sha"]
    else:
        raise Exception(f"Error getting file SHA: {response.json()}")


def delete_file(file_path):
    url = f"{API_URL}/contents/{file_path}"
    data = {
        "message": f"Deleting file: {file_path}",
        "sha": get_file_sha(file_path),
        "branch": BASE_BRANCH,
    }
    response = requests.delete(url, headers=HEADERS, json=data)

    if not response.status_code == 200 and not response.status_code == 404:
        raise Exception(f"Error deleting file: {response.json()}")


def create_or_update_file(file_path, content, commit_message):
    url = f"{API_URL}/contents/{file_path}"
    b = base64.b64encode(bytes(content, "utf-8"))
    base64_str = b.decode("utf-8")

    # Check if file exists
    response = requests.get(url, headers=HEADERS)
    if response.status_code == 200:
        sha = response.json()["sha"]
    else:
        sha = None

    data = {
        "message": commit_message,
        "content": base64_str,
        "branch": BASE_BRANCH,
    }

    if sha:
        data["sha"] = sha  # If file exists, update it

    response = requests.put(url, headers=HEADERS, json=data)
    if not response.status_code in [200, 201]:
        raise Exception(f"Error committing file: {response.json()}")