#!/usr/bin/env python3
"""
Queue Campaign from Batch
Queues all customers from a specific campaign batch into Lia's workflow (campaign_pool).
"""
import argparse
import sys
import os
from typing import List, Dict, Any
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from utils.tools import get_client


def get_campaign_batch(tag: str) -> Dict[str, Any]:
    """
    Look up campaign_batch by tag.
    
    Args:
        tag: Campaign batch tag
    
    Returns:
        Dict with id and summary
    
    Raises:
        SystemExit if batch not found
    """
    client = get_client()
    
    result = client.table('campaign_batch') \
        .select('id, tag, summary') \
        .eq('tag', tag) \
        .execute()
    
    if not result.data or len(result.data) == 0:
        print(f"❌ Campaign batch not found: {tag}")
        sys.exit(1)
    
    return result.data[0]


def get_batch_items(batch_id: int) -> List[int]:
    """
    Get all agreement IDs from campaign_batch_item for this batch.
    
    Args:
        batch_id: Campaign batch ID
    
    Returns:
        List of unique agreement IDs
    """
    client = get_client()
    
    result = client.table('campaign_batch_item') \
        .select('agreement_id') \
        .eq('batch_id', batch_id) \
        .execute()
    
    # Get unique agreement IDs
    agreement_ids = list(set(row['agreement_id'] for row in result.data))
    return agreement_ids


def get_existing_pool_items(tag: str, agreement_ids: List[int]) -> set:
    """
    Get agreement IDs already in campaign_pool for this tag.
    
    Args:
        tag: Campaign tag
        agreement_ids: List of agreement IDs to check
    
    Returns:
        Set of agreement IDs already queued for this tag
    """
    client = get_client()
    
    result = client.table('campaign_pool') \
        .select('agreement_id') \
        .eq('campaign_tag', tag) \
        .in_('agreement_id', agreement_ids) \
        .execute()
    
    return {row['agreement_id'] for row in result.data}


def queue_agreements(tag: str, agreement_ids: List[int], channel: str, existing: set) -> int:
    """
    Insert agreements into campaign_pool.
    
    Args:
        tag: Campaign tag
        agreement_ids: List of agreement IDs to queue
        channel: Communication channel
        existing: Set of existing agreement IDs already queued
    
    Returns:
        Number of agreements queued
    """
    client = get_client()
    
    # Filter out duplicates
    new_ids = [aid for aid in agreement_ids if aid not in existing]
    
    if not new_ids:
        return 0
    
    # Build insert records
    records = [{
        'agreement_id': aid,
        'campaign_tag': tag,
        'channel': channel,
        'status': 'queued',
        'source': 'manager_batch'
    } for aid in new_ids]
    
    # Batch insert
    client.table('campaign_pool') \
        .insert(records) \
        .execute()
    
    return len(records)


def run(tag: str, channel: str) -> None:
    """
    Main queue logic.
    
    Args:
        tag: Campaign batch tag
        channel: Communication channel
    """
    print("=" * 80)
    print("🎯 QUEUE CAMPAIGN FROM BATCH")
    print("=" * 80)
    print(f"Tag: {tag}")
    print(f"Channel: {channel}")
    print()
    
    # Step 1: Look up campaign_batch
    print(f"📋 Looking up campaign batch...")
    batch = get_campaign_batch(tag)
    batch_id = batch['id']
    summary = batch.get('summary', 'N/A')
    
    print(f"   ✅ Found batch (ID: {batch_id})")
    print(f"   Summary: {summary}")
    
    # Step 2: Get all batch items
    print(f"\n🔍 Fetching batch items...")
    agreement_ids = get_batch_items(batch_id)
    total = len(agreement_ids)
    
    print(f"   Found {total} unique agreement(s)")
    
    if total == 0:
        print("\n   ℹ️  No agreements to queue")
        print("=" * 80)
        return
    
    # Step 3: Check for existing pool items
    print(f"\n🔄 Checking for duplicates in campaign_pool...")
    existing = get_existing_pool_items(tag, agreement_ids)
    duplicates = len(existing)
    
    print(f"   Already queued: {duplicates}")
    
    # Step 4: Queue new agreements
    print(f"\n📤 Queueing agreements...")
    queued = queue_agreements(tag, agreement_ids, channel, existing)
    
    print(f"   Queued: {queued}")
    print(f"   Skipped (duplicates): {duplicates}")
    
    # Summary
    print("\n" + "=" * 80)
    print(f"✨ SUMMARY")
    print("=" * 80)
    print(f"Queued {queued} agreements for campaign {tag} (channel={channel})")
    print(f"Skipped {duplicates} duplicates")
    print(f'Summary = "{summary}"')
    print("=" * 80)


def main():
    """CLI entry point."""
    parser = argparse.ArgumentParser(
        description="Queue all customers from a campaign batch into Lia's workflow"
    )
    parser.add_argument(
        '--tag',
        required=True,
        help='Campaign batch tag (e.g., A5-Upgrade-Nov-Wk2)'
    )
    parser.add_argument(
        '--channel',
        default='whatsapp',
        help='Communication channel (default: whatsapp)'
    )
    
    args = parser.parse_args()
    
    try:
        run(args.tag, args.channel)
    except Exception as e:
        print(f"\n❌ Fatal error: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()
