#!/usr/bin/env python3

import os
import re
import yaml
import json
import requests
from pathlib import Path

def get_latest_version(package_config, headers):
    owner, repo = package_config['github_repo'].split('/')
    
    if package_config['version_method'] == 'release':
        url = f'https://api.github.com/repos/{owner}/{repo}/releases/latest'
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            version = response.json()['tag_name']
    else:  # tag method
        url = f'https://api.github.com/repos/{owner}/{repo}/tags'
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            version = response.json()[0]['name']

    if 'version_pattern' in package_config:
        match = re.match(package_config['version_pattern'], version)
        if match:
            version = match.group(1)

    return version.lstrip('v')

def get_current_version(pkgbuild_path):
    with open(pkgbuild_path, 'r') as f:
        content = f.read()
        match = re.search(r'pkgver=([^\n]+)', content)
        return match.group(1) if match else None

def main():
    with open('aur-packages.yml', 'r') as f:
        config = yaml.safe_load(f)

    headers = {
        'Authorization': f'token {os.environ["GITHUB_TOKEN"]}',
        'Accept': 'application/vnd.github.v3+json'
    }

    updates = []
    for package_name, package_config in config['packages'].items():
        try:
            latest_version = get_latest_version(package_config, headers)
            current_version = get_current_version(package_config['pkgbuild_path'])

            if latest_version != current_version:
                updates.append({
                    'name': package_name,
                    'current': current_version,
                    'latest': latest_version
                })
                print(f"Update available for {package_name}: {current_version} -> {latest_version}")

        except Exception as e:
            print(f"Error processing {package_name}: {str(e)}")

    # Write output for GitHub Actions
    with open(os.environ['GITHUB_OUTPUT'], 'w') as f:
        f.write(f"updates_needed={'true' if updates else 'false'}\n")
        f.write(f"updates_list={json.dumps(updates)}\n")

if __name__ == "__main__":
    main() 