#!/usr/bin/env python3
"""Debug script to test Excel parsing and see what Docling extracts from each sheet."""

import asyncio
import sys
from pathlib import Path
from uuid import uuid4

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

from src.extraction_v2.excel_parser_service import get_excel_parser_service


async def debug_parse_excel(file_path: str):
    """Debug Excel parsing to see what content is extracted from each sheet."""
    print(f"\n{'='*80}")
    print(f"DEBUG: Parsing Excel file: {file_path}")
    print(f"{'='*80}\n")

    # Read file content
    with open(file_path, 'rb') as f:
        file_content = f.read()

    # Get parser service
    parser_service = get_excel_parser_service()

    # Parse file
    file_id = uuid4()
    original_filename = Path(file_path).name

    print(f"File ID: {file_id}")
    print(f"Original filename: {original_filename}")
    print(f"File size: {len(file_content)} bytes\n")

    # Parse
    chunks = await parser_service.parse_excel_file(
        file_content=file_content,
        file_id=file_id,
        original_filename=original_filename,
        max_characters=4000,
    )

    print(f"\n{'='*80}")
    print(f"RESULTS: Total chunks: {len(chunks)}")
    print(f"{'='*80}\n")

    # Group chunks by sheet
    sheets = {}
    for chunk in chunks:
        sheet_name = chunk.metadata.get('sheet_name', 'Unknown')
        if sheet_name not in sheets:
            sheets[sheet_name] = []
        sheets[sheet_name].append(chunk)

    # Print summary by sheet
    print("\nChunks by sheet:")
    for sheet_name, sheet_chunks in sheets.items():
        print(f"\n  {sheet_name}: {len(sheet_chunks)} chunks")
        for idx, chunk in enumerate(sheet_chunks, 1):
            element_type = chunk.element_type
            text_preview = chunk.text[:100] if len(chunk.text) > 100 else chunk.text
            print(f"    Chunk {idx} ({element_type}): {text_preview}...")

    # Check for target sheets
    target_sheets = ['ステータス戻し実施可否判定', 'チェック対象判定']
    print(f"\n{'='*80}")
    print("TARGET SHEETS CHECK:")
    print(f"{'='*80}\n")
    for target in target_sheets:
        if target in sheets:
            print(f"✓ {target}: {len(sheets[target])} chunks found")
        else:
            print(f"✗ {target}: NO CHUNKS FOUND!")

    return chunks


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python debug_excel_parsing.py <path_to_excel_file>")
        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)

    asyncio.run(debug_parse_excel(file_path))
