#!/usr/bin/env python3
"""Debug script to see full Docling markdown output."""

import asyncio
import sys
import tempfile
import subprocess
from pathlib import Path

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

from docling.document_converter import DocumentConverter


def convert_xls_to_xlsx(xls_path: str) -> str:
    """Convert .xls to .xlsx using LibreOffice."""
    temp_dir = tempfile.mkdtemp()
    result = subprocess.run([
        'soffice',
        '--headless',
        '--convert-to', 'xlsx',
        '--outdir', temp_dir,
        xls_path
    ], capture_output=True, text=True, timeout=30)

    if result.returncode != 0:
        raise Exception(f"LibreOffice conversion failed: {result.stderr}")

    # Find the converted file
    xlsx_file = list(Path(temp_dir).glob('*.xlsx'))[0]
    return str(xlsx_file)


def main(file_path: str):
    """Show full Docling markdown output."""
    print(f"Converting file: {file_path}\n")

    # Convert if needed
    if file_path.endswith('.xls'):
        xlsx_path = convert_xls_to_xlsx(file_path)
        print(f"Converted to: {xlsx_path}\n")
    else:
        xlsx_path = file_path

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

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

    print(f"Total markdown length: {len(markdown)} characters")
    print(f"\n{'='*80}")
    print("FULL MARKDOWN OUTPUT:")
    print(f"{'='*80}\n")
    print(markdown)

    # Search for target sheets
    print(f"\n{'='*80}")
    print("SEARCHING FOR TARGET SHEETS:")
    print(f"{'='*80}\n")

    target_sheets = ['ステータス戻し実施可否判定', 'チェック対象判定']
    for target in target_sheets:
        if target in markdown:
            print(f"✓ Found '{target}' in markdown")
            # Find the section
            idx = markdown.find(target)
            start = max(0, idx - 100)
            end = min(len(markdown), idx + 500)
            print(f"  Context:\n{markdown[start:end]}\n")
        else:
            print(f"✗ '{target}' NOT found in markdown")


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

    main(sys.argv[1])
