#!/usr/bin/env python3

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

def clone_aur_package(package_name):
    """Clone an AUR package repository if it doesn't exist."""
    if not os.path.exists(package_name):
        subprocess.run([
            'git', 'clone',
            f'https://aur.archlinux.org/{package_name}.git'
        ], check=True)

def get_current_version(pkgbuild_path):
    """Extract current version from PKGBUILD."""
    with open(pkgbuild_path, 'r') as f:
        content = f.read()
        match = re.search(r'pkgver=([^\n]+)', content)
        if match:
            # Strip quotes and 'v' prefix if it exists to normalize version numbers
            return match.group(1).strip('"\'').lstrip('v')
        return None

def run_nvchecker():
    """Run nvchecker and return the results."""
    # Set GitHub token for nvchecker
    env = os.environ.copy()
    if 'GITHUB_TOKEN' in env:
        env['NVCHECKER_GITHUB_TOKEN'] = env['GITHUB_TOKEN']
    
    try:
        # Run nvchecker
        result = subprocess.run([
            'nvchecker', '-c', 'nvchecker.toml'
        ], env=env, capture_output=True, text=True, check=True)
        
        print("nvchecker output:")
        print(result.stdout)
        if result.stderr:
            print("nvchecker stderr:")
            print(result.stderr)
        
        # Read the results from newver.json
        if os.path.exists('newver.json'):
            with open('newver.json', 'r') as f:
                result = json.load(f)
                # nvchecker 2.x format has version and data fields
                if 'data' in result:
                    return {name: info['version'] for name, info in result['data'].items()}
                else:
                    # Fallback for older format
                    return result
        else:
            print("No newver.json file created by nvchecker")
            return {}
            
    except subprocess.CalledProcessError as e:
        print(f"nvchecker failed: {e}")
        print(f"stdout: {e.stdout}")
        print(f"stderr: {e.stderr}")
        return {}

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

    # Run nvchecker to get latest versions
    latest_versions = run_nvchecker()
    print(f"nvchecker found versions: {latest_versions}")

    updates = []
    for package_name, package_config in config['packages'].items():
        try:
            # Skip packages marked as fixed_version
            if package_config.get('fixed_version', False):
                print(f"Skipping version check for {package_name} (fixed version package)")
                continue
                
            # Clone the AUR package repository first
            clone_aur_package(package_name)
            
            # Get versions
            latest_version = latest_versions.get(package_name)
            if latest_version is None:
                print(f"No version found by nvchecker for {package_name}")
                continue
                
            # Strip 'v' prefix from nvchecker result if present
            latest_version = latest_version.lstrip('v')
            
            current_version = get_current_version(package_config['pkgbuild_path'])
            if current_version is None:
                print(f"Could not extract current version for {package_name}")
                continue

            print(f"{package_name}: current={current_version}, latest={latest_version}")

            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}")
            elif package_config.get('force_update', False):
                # Include package in updates if force_update flag is set, even if version is the same
                updates.append({
                    'name': package_name,
                    'current': current_version,
                    'latest': current_version,  # Use current as latest since no new version
                    'force_update': True
                })
                print(f"Forcing update for {package_name} (version {current_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")
    
    print(f"Found {len(updates)} packages needing updates")

if __name__ == "__main__":
    main()