#!/usr/bin/env python3
"""
Automated Availability Checker - Runs periodically
Can be used with cron or as a daemon
"""
import schedule
import time
import subprocess
from datetime import datetime
from pathlib import Path

def run_availability_check():
    """Run the availability check script"""
    print("\n" + "=" * 70)
    print(f"🕐 Scheduled Check Starting - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 70)

    script_dir = Path(__file__).parent
    check_script = script_dir / "check_availability.py"

    try:
        # Run the check script
        result = subprocess.run(
            ['python3', str(check_script)],
            cwd=str(script_dir),
            capture_output=True,
            text=True,
            timeout=3600  # 1 hour timeout
        )

        print(result.stdout)
        if result.stderr:
            print("Errors:", result.stderr)

        print("\n✅ Scheduled check completed")

    except subprocess.TimeoutExpired:
        print("❌ Check timed out after 1 hour")
    except Exception as e:
        print(f"❌ Error running check: {e}")

def run_scheduler(check_time="03:00"):
    """
    Run scheduled availability checks

    Args:
        check_time: Time to run daily check (24-hour format, e.g., "03:00")
    """
    print("🤖 Automated Availability Checker - Starting")
    print("=" * 70)
    print(f"Daily check scheduled at: {check_time}")
    print(f"Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("\nPress Ctrl+C to stop")
    print("=" * 70)

    # Schedule daily check
    schedule.every().day.at(check_time).do(run_availability_check)

    # Run immediately on startup (optional)
    run_immediately = input("\nRun availability check now? [y/N]: ").lower()
    if run_immediately == 'y':
        run_availability_check()

    print("\n⏰ Scheduler running... (Ctrl+C to stop)")

    try:
        while True:
            schedule.run_pending()
            time.sleep(60)  # Check every minute
    except KeyboardInterrupt:
        print("\n\n🛑 Scheduler stopped")

if __name__ == "__main__":
    import sys

    if len(sys.argv) > 1:
        check_time = sys.argv[1]
        run_scheduler(check_time)
    else:
        run_scheduler("03:00")  # Default: 3 AM
