#!/usr/bin/env python3
"""
Appointment Reminder Sender
Sends WhatsApp reminders for upcoming renewal appointments.
"""
import argparse
import sys
import os
from datetime import datetime, timezone
from typing import List, Dict, Any, Optional

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from utils.tools import get_client, log_message


def get_reminder_template(channel: str = 'whatsapp') -> Optional[str]:
    """
    Get appt_reminder template body.
    
    Args:
        channel: Communication channel (default: whatsapp)
    
    Returns:
        Template body or None
    """
    client = get_client()
    
    result = client.table('reply_template') \
        .select('body') \
        .eq('slug', 'appt_reminder') \
        .eq('channel', channel) \
        .eq('active', True) \
        .execute()
    
    if result.data and len(result.data) > 0:
        return result.data[0]['body']
    
    return None


def get_reminders(limit: int) -> List[Dict[str, Any]]:
    """
    Get appointment reminders from v_appt_reminder_queue view.
    
    Args:
        limit: Maximum number of reminders to fetch
    
    Returns:
        List of reminder records
    """
    client = get_client()
    
    result = client.table('v_appt_reminder_queue') \
        .select('*') \
        .order('preferred_date') \
        .limit(limit) \
        .execute()
    
    return result.data if result.data else []


def render_reminder_message(template_body: str, row: Dict[str, Any]) -> str:
    """
    Render reminder message with placeholders.
    
    Args:
        template_body: Template string
        row: Reminder row data
    
    Returns:
        Rendered message text
    """
    text = template_body
    text = text.replace('{{first_name}}', row.get('first_name', ''))
    text = text.replace('{{centre_name}}', 'Lincoln Audi')
    text = text.replace('{{model}}', row.get('model', 'Audi'))
    
    return text.strip()


def update_reminder_sent(appt_id: int, channel: str, dry_run: bool = False) -> bool:
    """
    Mark appointment_request as reminder sent.
    
    Args:
        appt_id: Appointment request ID
        channel: Communication channel
        dry_run: If True, skip actual update
    
    Returns:
        True if successful, False otherwise
    """
    if dry_run:
        return True
    
    try:
        client = get_client()
        now_utc = datetime.now(timezone.utc)
        
        client.table('appointment_request') \
            .update({
                'reminder_sent_at': now_utc.isoformat(),
                'reminder_channel': channel
            }) \
            .eq('id', appt_id) \
            .execute()
        
        return True
    
    except Exception as e:
        print(f"      ❌ Error updating appointment {appt_id}: {e}")
        return False


def run(channel: str, limit: int, dry_run: bool) -> None:
    """
    Main send logic.
    
    Args:
        channel: Communication channel
        limit: Maximum reminders to send
        dry_run: If True, preview only (no writes)
    """
    print("=" * 80)
    print("📅 APPOINTMENT REMINDER SENDER")
    print("=" * 80)
    print(f"Channel: {channel}")
    print(f"Limit: {limit}")
    if dry_run:
        print("🔍 DRY RUN MODE (no writes)")
    print()
    
    # Get template
    print(f"📝 Loading appt_reminder template...")
    template_body = get_reminder_template(channel)
    
    if not template_body:
        print(f"   ❌ Template 'appt_reminder' not found for channel '{channel}' or inactive")
        sys.exit(1)
    
    print(f"   ✅ Template loaded ({len(template_body)} chars)")
    
    # Get reminders
    print(f"\n🔍 Fetching reminders from v_appt_reminder_queue (limit={limit})...")
    reminders = get_reminders(limit)
    total = len(reminders)
    
    print(f"   Found {total} reminder(s) to send")
    
    if total == 0:
        print("\n   ℹ️  No reminders to send")
        print("=" * 80)
        return
    
    # Send reminders
    print(f"\n📤 Sending reminders...")
    sent_count = 0
    error_count = 0
    
    for idx, row in enumerate(reminders, 1):
        appt_id = row['appt_id']
        agreement_number = row.get('agreement_number', 'UNKNOWN')
        first_name = row.get('first_name', '')
        preferred_date = row.get('preferred_date', 'TBD')
        
        print(f"\n   [{idx}/{total}] {agreement_number} ({first_name})")
        print(f"      Appointment: {preferred_date}")
        
        # Render message
        message_text = render_reminder_message(template_body, row)
        
        if dry_run:
            print(f"      [DRY RUN] Would send: \"{message_text[:60]}...\"")
            sent_count += 1
        else:
            # Log to contact_history
            try:
                log_message(
                    agreement_ref=agreement_number,
                    channel=channel,
                    direction='outbound',
                    message_text=message_text,
                    intent_label='appt_reminder',
                    template_slug='appt_reminder',
                    source='ai',
                    model=None
                )
                
                # Update appointment_request
                if update_reminder_sent(appt_id, channel, dry_run=False):
                    sent_count += 1
                    print(f"      ✅ Sent and logged")
                else:
                    error_count += 1
                    print(f"      ⚠️  Logged but failed to update appointment")
            
            except Exception as e:
                error_count += 1
                print(f"      ❌ Error sending: {e}")
    
    # Summary
    print("\n" + "=" * 80)
    print(f"✨ SUMMARY")
    print("=" * 80)
    print(f"Total reminders considered: {total}")
    print(f"Successfully sent: {sent_count}")
    if error_count > 0:
        print(f"Errors: {error_count}")
    if dry_run:
        print("\n⚠️  DRY RUN: No data was written to database")
    print("=" * 80)


def main():
    """CLI entry point."""
    parser = argparse.ArgumentParser(
        description='Send appointment reminder messages for upcoming renewals'
    )
    parser.add_argument(
        '--channel',
        default='whatsapp',
        help='Communication channel (default: whatsapp)'
    )
    parser.add_argument(
        '--limit',
        type=int,
        default=50,
        help='Maximum reminders to send (default: 50)'
    )
    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='Preview mode - show what would be sent without writing to database'
    )
    
    args = parser.parse_args()
    
    run(
        channel=args.channel,
        limit=args.limit,
        dry_run=args.dry_run
    )


if __name__ == "__main__":
    main()
