#!/usr/bin/env python3
"""Quick test for .xls file support in V2 pipeline."""

import sys
from pathlib import Path
from src.db.session import get_sync_session
from src.db import models as db_models
from src.extraction_v2.pipeline import ExtractionPipelineV2

# Test .xls file (using filesystem-encoded path)
xls_file = "./AIHackathonFolder/Phase2/CustomerDocument/чФ╗щЭвшиншиИч╖и/01_хЕ▒щАЪ/02_чФ╗щЭвщБ╖чз╗хЫ│/01.01.02.02.07_чФ╗щЭвщБ╖чз╗хЫ│_х╖еф║ЛцГЕха▒ц╡БщАЪ-я╝вя╝пчК╢ц│БхЗ║хКЫщГихИЖ.xls"

def test_xls_file():
    """Test V2 pipeline with .xls file."""
    print("=" * 80)
    print("TESTING .XLS FILE SUPPORT IN V2 PIPELINE")
    print("=" * 80)
    print(f"\nFile: {xls_file}")

    file_path = Path(xls_file)
    if not file_path.exists():
        print(f"✗ ERROR: File not found: {xls_file}")
        return False

    print(f"✓ File exists ({file_path.stat().st_size / 1024:.1f} KB)")

    try:
        # Create test document
        with get_sync_session() as session:
            doc = db_models.Document(
                filename=file_path.name,
                file_path=str(file_path.absolute()),
                status="pending"
            )
            session.add(doc)
            session.commit()
            doc_id = doc.id

            print(f"\n✓ Created document record (ID: {doc_id})")

            # Run V2 pipeline
            print(f"\nRunning V2 extraction pipeline...")
            print("-" * 80)

            v2_pipeline = ExtractionPipelineV2()
            result = v2_pipeline.process_document_sync(doc_id, str(file_path.absolute()))

            print("-" * 80)

            if result.success:
                print(f"\n✓ SUCCESS!")
                print(f"  Records extracted: {result.record_count}")
                print(f"  Tables detected: {result.table_count}")

                # Show sheet distribution
                from collections import Counter
                sheet_counts = Counter(r['_source']['sheet'] for r in result.records)
                print(f"  Sheets found:")
                for sheet, count in sheet_counts.items():
                    print(f"    - {sheet}: {count} records")

                print(f"\n✓ .XLS file successfully processed through V2 pipeline!")
                return True
            else:
                print(f"\n✗ FAILED")
                print(f"  Error: {result.error}")
                return False

    except Exception as e:
        print(f"\n✗ EXCEPTION: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = test_xls_file()
    sys.exit(0 if success else 1)
