import os
import sys
import json
import urllib.request
import urllib.error
import time

def get_action_runs(server_url, repo, token, limit=1):
    url = f"{server_url}/api/v1/repos/{repo}/actions/runs?limit={limit}"
    req = urllib.request.Request(url)
    req.add_header("Authorization", f"token {token}")
    
    try:
        with urllib.request.urlopen(req) as response:
            return json.loads(response.read().decode())
    except urllib.error.HTTPError as e:
        print(f"Error fetching action runs: {e.code} {e.reason}")
        return None
    except Exception as e:
        print(f"Error: {str(e)}")
        return None

def monitor_run(server_url, repo, token, run_id):
    url = f"{server_url}/api/v1/repos/{repo}/actions/runs/{run_id}"
    req = urllib.request.Request(url)
    req.add_header("Authorization", f"token {token}")
    
    try:
        with urllib.request.urlopen(req) as response:
            return json.loads(response.read().decode())
    except Exception as e:
        print(f"Error monitoring run: {str(e)}")
        return None

def main():
    if len(sys.argv) < 4:
        print("Usage: python3 gitea_action_monitor.py <server_url> <repo> <token>")
        sys.exit(1)
        
    server_url = sys.argv[1].rstrip('/')
    repo = sys.argv[2]
    token = sys.argv[3]
    
    print(f"Checking Gitea Actions for {repo}...")
    
    runs_data = get_action_runs(server_url, repo, token)
    if not runs_data or not runs_data.get('workflow_runs'):
        print("No action runs found.")
        return
        
    latest_run = runs_data['workflow_runs'][0]
    run_id = latest_run['id']
    status = latest_run['status']
    conclusion = latest_run.get('conclusion', 'unknown')
    name = latest_run.get('name', 'unnamed')
    
    print(f"Latest Run: {name} (ID: {run_id})")
    print(f"Status: {status}")
    
    if status == "running":
        print("Waiting for completion...")
        for _ in range(10): # Max 10 attempts
            time.sleep(10)
            run_data = monitor_run(server_url, repo, token, run_id)
            if not run_data: break
            status = run_data['status']
            if status != "running":
                conclusion = run_data.get('conclusion', 'unknown')
                break
            print(".", end="", flush=True)
        print(f"\nFinal Status: {status} ({conclusion})")
    else:
        print(f"Conclusion: {conclusion}")

if __name__ == "__main__":
    main()
