"""
Regenerate AI outfit matches — clear old + run full batch.

Usage:
  py backend/worker/scripts/regenerate_matches.py          # run all
  py backend/worker/scripts/regenerate_matches.py --limit 10  # dry-run 10 products
  py backend/worker/scripts/regenerate_matches.py --execute --limit 50  # commit 50 products
"""

import argparse
import sqlite3
import sys
import time
from pathlib import Path

# Add backend to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from common.constants import SQLITE_DB_PATH

def clear_old_matches(dry_run: bool = True) -> int:
    """Xóa tất cả matches cũ. Returns số bản ghi bị xóa."""
    conn = None
    try:
        conn = sqlite3.connect(SQLITE_DB_PATH)
        cur = conn.cursor()

        if dry_run:
            cur.execute("SELECT COUNT(*) FROM pg__dashboard_canifa__ai_outfit_product_matches")
            count = cur.fetchone()[0]
            print(f"[DRY-RUN] Sẽ xóa {count} bản ghi cũ trong pg__dashboard_canifa__ai_outfit_product_matches")
            return count
        else:
            cur.execute("DELETE FROM pg__dashboard_canifa__ai_outfit_product_matches")
            deleted = cur.rowcount
            conn.commit()
            print(f"[EXECUTE] Đã xóa {deleted} bản ghi cũ")
            return deleted
    finally:
        if conn:
            conn.close()

def run_batch(limit: int | None = None, dry_run: bool = False):
    """Chạy StylistEngine batch."""
    from worker.stylist_engine import StylistEngine, BATCH_STATE

    print(f"\n{'='*60}")
    print(f"🚀 CANIFA OUTFIT REGENERATION")
    print(f"{'='*60}")
    print(f"Mode: {'DRY-RUN' if dry_run else 'EXECUTE'}")
    print(f"Limit: {limit or 'ALL'}")
    print(f"{'='*60}\n")

    # Clear old matches
    print("🗑️  Clearing old matches...")
    clear_old_matches(dry_run=dry_run)

    # Get list of codes to process
    print("\n📦 Loading catalog...")
    engine = StylistEngine()
    catalog = engine._get_catalog()
    all_codes = [p["code"] for p in catalog]
    if limit:
        codes = all_codes[:limit]
    else:
        codes = all_codes
    print(f"   Found {len(codes)} products to process (from {len(all_codes)} total)")

    # Run batch directly with codes list
    print("\n🔄 Running StylistEngine batch...\n")
    start = time.time()
    count = engine.run_batch(codes=codes)
    elapsed = time.time() - start

    print(f"\n{'='*60}")
    print(f"✅ Batch completed in {elapsed:.1f}s")
    print(f"   Processed: {count} products")
    print(f"   BATCH_STATE: {BATCH_STATE}")
    print(f"{'='*60}\n")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--limit", type=int, default=None, help="Giới hạn số SP xử lý")
    parser.add_argument("--execute", action="store_true", help="Thực sự xóa và lưu (không dry-run)")
    args = parser.parse_args()

    run_batch(limit=args.limit, dry_run=not args.execute)
