#!/usr/bin/env python3
"""Test Docling on clean Excel file without preprocessing."""

import sys
import subprocess
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from docling.document_converter import DocumentConverter


def convert_xls(xls_path: str) -> str:
    """Convert .xls to .xlsx."""
    temp_dir = tempfile.mkdtemp()
    result = subprocess.run([
        '/Applications/LibreOffice.app/Contents/MacOS/soffice',
        '--headless',
        '--convert-to', 'xlsx',
        '--outdir', temp_dir,
        xls_path
    ], capture_output=True, text=True, timeout=60)

    xlsx_files = list(Path(temp_dir).glob('*.xlsx'))
    return str(xlsx_files[0]) if xlsx_files else None


def main(file_path: str):
    """Test Docling extraction on clean file."""
    print(f"Testing Docling on: {file_path}\n")

    # Convert
    xlsx_path = convert_xls(file_path)
    print(f"Converted to: {xlsx_path}\n")

    # Convert with Docling
    converter = DocumentConverter()
    result = converter.convert(Path(xlsx_path))

    # Export markdown
    markdown = result.document.export_to_markdown()

    # Search for target sheets
    target_sheets = ['ステータス戻し実施可否判定', 'チェック対象判定']

    print(f"Total markdown length: {len(markdown)} characters\n")
    print(f"{'='*80}")
    print("SEARCHING FOR TARGET SHEET TEXT:")
    print(f"{'='*80}\n")

    for target in target_sheets:
        print(f"\n--- {target} ---")
        if target in markdown:
            idx = markdown.find(target)
            start = max(0, idx - 50)
            end = min(len(markdown), idx + 500)
            print(f"FOUND at position {idx}:")
            print(markdown[start:end])
        else:
            print("NOT FOUND in markdown!")

        # Also search for the first text we expect
        if target == 'ステータス戻し実施可否判定':
            search_text = '２.１.３.１.１'
            if search_text in markdown:
                print(f"\n✓ Found expected text '{search_text}'")
            else:
                print(f"\n✗ Expected text '{search_text}' NOT FOUND")

        if target == 'チェック対象判定':
            search_text = '２.１.３.１.２'
            if search_text in markdown:
                print(f"\n✓ Found expected text '{search_text}'")
            else:
                print(f"\n✗ Expected text '{search_text}' NOT FOUND")


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

    main(sys.argv[1])
