#!/usr/bin/env python3
"""
Luzia's autonomous request approval loop
Runs as part of luzia's core orchestration responsibilities
"""

import subprocess
import sys
import time
from pathlib import Path

def run_request_cycle():
    """Execute one cycle of request processing"""
    handler = Path("/opt/server-agents/orchestrator/lib/request_handler.py")
    
    try:
        result = subprocess.run(
            ['python3', str(handler), '--background'],
            capture_output=True,
            text=True,
            timeout=30
        )
        return result.stdout, result.returncode
    except subprocess.TimeoutExpired:
        return "Request cycle timeout", 1
    except Exception as e:
        return f"Request cycle error: {e}", 1

def main():
    """Main loop - runs request approver every 5 minutes"""
    print("🔄 Luzia Request Approver loop started")
    print("Checking requests every 5 minutes...")
    
    cycle = 0
    while True:
        cycle += 1
        print(f"\n[Cycle {cycle}] Checking pending requests...")
        
        output, rc = run_request_cycle()
        if rc == 0 and output:
            # Log cycle result (last line)
            lines = output.strip().split('\n')
            for line in lines[-3:]:
                print(f"  {line}")
        else:
            print(f"  ⚠️  Cycle failed: {output}")
        
        # Sleep 5 minutes before next cycle
        time.sleep(300)

if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == '--once':
        # Run once and exit
        output, rc = run_request_cycle()
        print(output)
        sys.exit(rc)
    else:
        # Run as background loop
        main()
