from dotenv import load_dotenv
from os import getenv
import base64
from github import Github

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")

g = Github(GITHUB_TOKEN)
repo = g.get_repo(f"{REPO_OWNER}/{REPO_NAME}")


def similar_exists(search_text):
    contents = repo.get_contents("_events")

    for content in contents:
        if content.type == "dir":
            return similar_exists(repo, content.path, search_text)
        elif content.type == "file":
            file_content = repo.get_contents(content.path)
            decoded_content = base64.b64decode(file_content.content).decode(
                "utf-8", errors="ignore"
            )
            if search_text in decoded_content:
                return True
    return False


def get_file(file_path):
    return repo.get_contents(file_path)


def delete_file(file_path):
    try:
        repo.delete_file(
            file_path,
            f"Deleting file: {file_path}",
            get_file(file_path).sha,
            BASE_BRANCH,
        )
    except Exception as e:
        if "404" in str(e):
            return


def create_or_update_file(file_path, content, commit_message):
    try:
        existing = get_file(file_path)
        repo.update_file(file_path, commit_message, content, existing.sha, BASE_BRANCH)
    except Exception as e:
        if "404" in str(e):
            repo.create_file(file_path, commit_message, content, BASE_BRANCH)