"""
Script to backfill inventory planning snapshot computation for the last X days
This triggers the Celery task for each day in the specified range
"""
import sys
from datetime import datetime, timedelta
from pathlib import Path

# Add the project root to the Python path
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

try:
    from src.smart_inventory.tasks.inventory_planning_task import compute_inventory_planning_snapshot
    print("[SUCCESS] Successfully imported compute_inventory_planning_snapshot task")
except ImportError as e:
    print(f"[ERROR] Error importing Celery task: {e}")
    print("Make sure Celery is running and the task module is available")
    sys.exit(1)


def run_inventory_planning_backfill(num_days: int):
    """
    Run inventory planning snapshot computation for the last X days
    
    Args:
        num_days: Number of days to backfill (going backwards from today)
    """
    # Calculate date range (from num_days ago to today)
    today = datetime.now().date()
    start_date = today - timedelta(days=num_days - 1)
    end_date = today
    
    print(f"\nDate range: {start_date} to {end_date} ({num_days} days)\n")
    
    # Confirmation
    response = input(f"Proceed? [y/N]: ").strip().lower()
    if response not in ['y', 'yes']:
        print("[CANCELLED]")
        return
    
    print()
    
    task_ids = []
    failed_dates = []
    
    # Loop through each day and trigger the task
    current_date = start_date
    for day_num in range(1, num_days + 1):
        date_str = current_date.strftime("%Y-%m-%d")
        
        try:
            print(f"[{day_num}/{num_days}] Triggering task for {date_str}...", end=" ")
            
            # Trigger the Celery task
            task = compute_inventory_planning_snapshot.delay(date_str)
            task_ids.append({
                'date': date_str,
                'task_id': task.id
            })
            
            print(f"[SUCCESS] Task ID: {task.id}")
            
        except Exception as e:
            print(f"[FAILED]")
            print(f"    Error: {str(e)}")
            failed_dates.append({
                'date': date_str,
                'error': str(e)
            })
        
        # Move to next day
        current_date += timedelta(days=1)
    
    # Summary
    print(f"\n{'='*60}")
    print(f"Tasks triggered: {len(task_ids)} | Failed: {len(failed_dates)}")
    print(f"{'='*60}\n")
    
    if task_ids:
        print("Successfully triggered:")
        for item in task_ids:
            print(f"   {item['date']} -> {item['task_id']}")
    
    if failed_dates:
        print(f"\nFailed:")
        for item in failed_dates:
            print(f"   {item['date']} -> {item['error']}")
    
    print(f"\n{'='*60}")
    print("Tasks are running in Celery. Check logs for progress.")
    print(f"{'='*60}\n")


def main():
    """Main entry point"""
    print("\nInventory Planning Celery Trigger for Backfill\n")
    
    # Get number of days from user
    while True:
        try:
            num_days_input = input("How many days to backfill: ").strip()
            
            if not num_days_input:
                print("[ERROR] Please enter a number")
                continue
            
            num_days = int(num_days_input)
            
            if num_days <= 0:
                print("[ERROR] Please enter a positive number")
                continue
            
            if num_days > 365:
                response = input(f"[WARNING] {num_days} days is more than 1 year. Continue? [y/N]: ").strip().lower()
                if response not in ['y', 'yes']:
                    continue
            
            break
            
        except ValueError:
            print("[ERROR] Invalid input. Please enter a valid number")
        except KeyboardInterrupt:
            print("\n[CANCELLED]")
            sys.exit(0)
    
    # Run the backfill
    try:
        run_inventory_planning_backfill(num_days)
    except KeyboardInterrupt:
        print("\n[CANCELLED]")
        sys.exit(1)
    except Exception as e:
        print(f"\n[ERROR] {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
