#!/usr/bin/env python3
"""Debug script to identify incorrectly split tables in V2 extraction."""

import sys
from pathlib import Path
from uuid import uuid4

from src.extraction_v2.pipeline import ExtractionPipelineV2


def debug_table_splits(file_path: str):
    """Debug table splitting issues."""

    print("=" * 80)
    print("TABLE SPLIT DEBUGGING")
    print("=" * 80)
    print(f"\nFile: {file_path}")

    # Run V2 extraction
    pipeline = ExtractionPipelineV2()
    result = pipeline.process_document_sync(uuid4(), file_path)

    if not result.success:
        print(f"\n❌ Extraction failed: {result.error}")
        return

    print(f"\n✓ Extraction complete: {len(result.records)} records from {result.table_count} tables")

    # Analyze records for suspicious headers
    print("\n" + "=" * 80)
    print("ANALYZING RECORDS FOR SUSPICIOUS HEADERS")
    print("=" * 80)

    suspicious_records = []

    for i, record in enumerate(result.records):
        content = record.get('content', {})
        source = record.get('_source', {})

        # Check for suspicious header patterns
        headers = list(content.keys())

        # Suspicious patterns:
        # 1. Numeric-only headers (e.g., "17", "33")
        # 2. "Column N" headers
        # 3. Headers with None
        # 4. Headers that look like data values (quoted strings, dashes)

        suspicious = False
        reasons = []

        # Check each header
        for header in headers:
            # Numeric headers
            if header.isdigit():
                suspicious = True
                reasons.append(f"Numeric header: '{header}'")

            # Column N headers
            if header.startswith("Column "):
                suspicious = True
                reasons.append(f"Generic header: '{header}'")

            # None headers
            if header == "None" or "None" in header:
                suspicious = True
                reasons.append(f"None header: '{header}'")

            # Data-like values in headers (quoted strings, dashes)
            if header.startswith("'") and header.endswith("'"):
                suspicious = True
                reasons.append(f"Quoted header: '{header}'")

            if header == "－" or header == "'－'":
                suspicious = True
                reasons.append(f"Dash header: '{header}'")

        if suspicious:
            suspicious_records.append({
                'index': i,
                'headers': headers,
                'content': content,
                'source': source,
                'reasons': reasons
            })

    # Report suspicious records
    if not suspicious_records:
        print("\n✓ No suspicious records found - all headers look correct!")
    else:
        print(f"\n⚠️  Found {len(suspicious_records)} suspicious record(s):")

        for rec in suspicious_records:
            print(f"\n--- Record {rec['index']} ---")
            print(f"Source: Sheet '{rec['source'].get('sheet')}', Row {rec['source'].get('row')}, Table {rec['source'].get('table_id')}")
            print(f"Headers: {rec['headers']}")
            print(f"Reasons:")
            for reason in rec['reasons']:
                print(f"  - {reason}")
            print(f"Content (first 3 values):")
            for key, value in list(rec['content'].items())[:3]:
                print(f"  '{key}': '{value}'")

    # Summary by table
    print("\n" + "=" * 80)
    print("SUMMARY BY TABLE")
    print("=" * 80)

    tables = {}
    for i, record in enumerate(result.records):
        source = record.get('_source', {})
        table_id = source.get('table_id', 0)

        if table_id not in tables:
            tables[table_id] = []
        tables[table_id].append(i)

    for table_id in sorted(tables.keys()):
        record_indices = tables[table_id]
        print(f"\nTable {table_id}: {len(record_indices)} records (indices {min(record_indices)}-{max(record_indices)})")

        # Check if any records in this table are suspicious
        suspicious_in_table = [rec for rec in suspicious_records if rec['source'].get('table_id') == table_id]
        if suspicious_in_table:
            print(f"  ⚠️  WARNING: {len(suspicious_in_table)} suspicious record(s) in this table")
            print(f"  This table may have been split incorrectly!")

    print("\n" + "=" * 80)
    print("DONE")
    print("=" * 80)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python debug_table_split.py <excel_file_path>")
        sys.exit(1)

    file_path = sys.argv[1]
    if not Path(file_path).exists():
        print(f"Error: File not found: {file_path}")
        sys.exit(1)

    debug_table_splits(file_path)
