#!/usr/bin/env python3
"""Find specific table by title in HTML output."""

import sys
from pathlib import Path
from bs4 import BeautifulSoup

from src.extraction_v2.excel_to_html_converter import ExcelToHtmlConverter


def find_table_by_title(file_path: str, title: str):
    """Find table with specific title in HTML."""

    print("=" * 80)
    print("FIND TABLE BY TITLE")
    print("=" * 80)
    print(f"\nFile: {file_path}")
    print(f"Looking for title: {title}")

    # Convert to HTML
    converter = ExcelToHtmlConverter()
    html = converter.convert_to_html(file_path)

    if not html:
        print("\n❌ Failed to convert to HTML")
        return

    print(f"\n✓ Converted to HTML ({len(html)} chars)")

    # Parse HTML
    soup = BeautifulSoup(html, 'lxml')

    # Find the title
    print(f"\n🔍 Searching for title: '{title}'")

    # Search in all text elements
    found = False
    for elem in soup.find_all(text=True):
        if title in elem:
            print(f"\n✓ Found title in <{elem.parent.name}> tag")
            found = True

            # Find the next table after this title
            current = elem.parent
            while current:
                next_sibling = current.find_next_sibling()
                if next_sibling:
                    table = next_sibling.find('table')
                    if table:
                        print(f"\n✓ Found table after title!")
                        print(f"Table HTML length: {len(str(table))} chars")

                        # Save to file
                        output_file = "debug_table_html.html"
                        with open(output_file, 'w', encoding='utf-8') as f:
                            f.write(f"<!-- Title: {title} -->\n")
                            f.write(str(table))

                        print(f"\n✓ Saved table HTML to: {output_file}")

                        # Parse table structure
                        rows = table.find_all('tr')
                        print(f"\nTable structure:")
                        print(f"  Rows: {len(rows)}")

                        if rows:
                            first_row = rows[0]
                            cells = first_row.find_all(['th', 'td'])
                            print(f"  First row cells: {len(cells)}")
                            print(f"  First row HTML: {str(first_row)[:200]}...")

                        # Show first 10 rows
                        print(f"\nFirst 10 rows:")
                        for i, row in enumerate(rows[:10]):
                            cells = row.find_all(['th', 'td'])
                            cell_texts = [cell.get_text(strip=True) for cell in cells]
                            print(f"  Row {i}: {cell_texts}")

                        return

                # Try next element
                current = current.find_next()
                if current and current.name == 'table':
                    print(f"\n✓ Found table immediately after title!")
                    print(f"Table HTML length: {len(str(current))} chars")

                    # Save to file
                    output_file = "debug_table_html.html"
                    with open(output_file, 'w', encoding='utf-8') as f:
                        f.write(f"<!-- Title: {title} -->\n")
                        f.write(str(current))

                    print(f"\n✓ Saved table HTML to: {output_file}")

                    # Parse table structure
                    rows = current.find_all('tr')
                    print(f"\nTable structure:")
                    print(f"  Rows: {len(rows)}")

                    if rows:
                        first_row = rows[0]
                        cells = first_row.find_all(['th', 'td'])
                        print(f"  First row cells: {len(cells)}")
                        print(f"  First row HTML: {str(first_row)[:200]}...")

                    # Show first 10 rows
                    print(f"\nFirst 10 rows:")
                    for i, row in enumerate(rows[:10]):
                        cells = row.find_all(['th', 'td'])
                        cell_texts = [cell.get_text(strip=True) for cell in cells]
                        print(f"  Row {i}: {cell_texts}")

                    return

                # Stop after checking a few elements
                if current and hasattr(current, 'name') and current.name in ['h1', 'h2', 'h3', 'p']:
                    # Move to next potential section
                    pass
                else:
                    break

    if not found:
        print(f"\n❌ Title not found in HTML")
        print("\nSearching for partial matches...")

        # Try partial match
        for elem in soup.find_all(text=True):
            text = elem.strip()
            if "SO工事結果" in text or "自動更新条件" in text:
                print(f"  Found partial match: '{text[:100]}'")


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

    # The title to search for
    title = "表 ４.２.１.４.４.６－１０－１　「所内SO工事結果」自動更新条件"

    find_table_by_title(file_path, title)
