from flask import Blueprint, render_template, redirect, url_for, flash, request, g
from app.models import db, User, Event, Guest, ScheduleItem
from app.auth import role_required
from datetime import datetime

caller_bp = Blueprint('caller', __name__, url_prefix='/caller')

@caller_bp.route('/dashboard')
@role_required('caller')
def dashboard():
    # Fetch events where this caller has at least one assigned guest
    # Query distinct events linked to the caller's guests
    assigned_event_ids = db.session.query(Guest.event_id).filter_by(caller_id=g.user.id).distinct().all()
    event_ids = [r[0] for r in assigned_event_ids]
    
    events = Event.query.filter(Event.id.in_(event_ids)).all() if event_ids else []
    
    # Compile statistics for each event for this caller
    event_stats = []
    for ev in events:
        my_guests = Guest.query.filter_by(event_id=ev.id, caller_id=g.user.id).all()
        total = len(my_guests)
        attending = sum(1 for gt in my_guests if gt.rsvp_status == 'attending')
        declined = sum(1 for gt in my_guests if gt.rsvp_status == 'not_attending')
        tentative = sum(1 for gt in my_guests if gt.rsvp_status == 'tentative')
        pending = sum(1 for gt in my_guests if gt.rsvp_status == 'pending')
        
        event_stats.append({
            'event': ev,
            'total': total,
            'attending': attending,
            'declined': declined,
            'tentative': tentative,
            'pending': pending
        })
        
    return render_template('caller/dashboard.html', event_stats=event_stats)

@caller_bp.route('/event/<int:event_id>')
@role_required('caller')
def rsvp_call(event_id):
    event = Event.query.get_or_404(event_id)
    
    # Fetch assigned guests for this event
    guests = Guest.query.filter_by(event_id=event.id, caller_id=g.user.id).order_by(Guest.name.asc()).all()
    
    if not guests:
        flash("You do not have any guests assigned for this event.", "warning")
        return redirect(url_for('caller.dashboard'))
        
    # Get schedule so caller can guide the guest
    schedule = ScheduleItem.query.filter_by(event_id=event.id).order_by(ScheduleItem.start_time.asc()).all()
    
    return render_template('caller/rsvp_call.html', event=event, guests=guests, schedule=schedule)

@caller_bp.route('/guest/<int:guest_id>/update-rsvp', methods=['POST'])
@role_required('caller')
def update_rsvp(guest_id):
    guest = Guest.query.get_or_404(guest_id)
    
    # Verify assignment
    if guest.caller_id != g.user.id:
        flash("Access Denied: You are not assigned to this guest.", "error")
        return redirect(url_for('caller.dashboard'))
        
    rsvp_status = request.form.get('rsvp_status', 'pending')
    arrival_details = request.form.get('arrival_details', '').strip()
    departure_details = request.form.get('departure_details', '').strip()
    notes = request.form.get('notes', '').strip()
    
    guest.rsvp_status = rsvp_status
    guest.arrival_details = arrival_details
    guest.departure_details = departure_details
    guest.notes = notes
    
    # Register the time if marked as completed
    if request.form.get('mark_done') == 'true':
        guest.call_completed_at = datetime.utcnow()
        
    db.session.commit()
    flash(f"RSVP details updated for {guest.name}.", "success")
    return redirect(url_for('caller.rsvp_call', event_id=guest.event_id))

@caller_bp.route('/guest/<int:guest_id>/complete-call', methods=['POST'])
@role_required('caller')
def complete_call(guest_id):
    guest = Guest.query.get_or_404(guest_id)
    
    # Verify assignment
    if guest.caller_id != g.user.id:
        flash("Access Denied: You are not assigned to this guest.", "error")
        return redirect(url_for('caller.dashboard'))
        
    guest.call_completed_at = datetime.utcnow()
    db.session.commit()
    
    flash(f"Call with {guest.name} successfully logged as completed/done.", "success")
    return redirect(url_for('caller.rsvp_call', event_id=guest.event_id))
