"""
Background job to auto-complete appointments after 24-hour review period expires
"""
from app.models import Appointment
from app.database import db
from app.utils.timezone import get_pakistan_now

def process_completion_reviews():
    """
    Auto-complete appointments where the 24-hour patient review period has expired
    Runs every hour via APScheduler
    """
    current_time = get_pakistan_now()
    
    # Find appointments pending review with expired deadlines
    expired_reviews = Appointment.query.filter(
        Appointment.status == 'completed_pending_review',
        Appointment.completion_review_deadline <= current_time
    ).all()
    
    for appointment in expired_reviews:
        # Auto-complete the appointment
        appointment.status = 'completed'
        appointment.patient_completed = True  # Assumed satisfied (no dispute)
        appointment.patient_completed_at = current_time
        appointment.completed_at = current_time
        
        # Credit doctor (80%) and record platform revenue (20%)
        try:
            from app.services.accounts_service import credit_doctor_after_completion
            credit_doctor_after_completion(appointment)
        except Exception as e:
            print(f'[AUTO-COMPLETE] Accounts credit failed for appointment #{appointment.id}: {e}')
        
        print(f'[AUTO-COMPLETE] Appointment #{appointment.id} - 24-hour review period expired')
    
    if expired_reviews:
        try:
            db.session.commit()
            print(f'✓ Auto-completed {len(expired_reviews)} appointment(s)')
        except Exception as e:
            db.session.rollback()
            print(f'Error auto-completing appointments: {e}')
    else:
        print('No appointments need auto-completion')

if __name__ == '__main__':
    # For manual testing
    from app import create_app
    app = create_app()
    
    with app.app_context():
        print("Running completion review processor...")
        process_completion_reviews()
        print("Processing complete!")
