#!/usr/bin/env python3
"""Save converted HTML to file for debugging."""

import sys
from pathlib import Path

from src.extraction_v2.excel_to_html_converter import ExcelToHtmlConverter


def save_html_output(file_path: str, output_path: str = "converted_output.html"):
    """Convert Excel to HTML and save to file."""

    print("=" * 80)
    print("SAVE HTML OUTPUT")
    print("=" * 80)
    print(f"\nInput file: {file_path}")
    print(f"Output file: {output_path}")

    # Convert to HTML
    print("\nConverting Excel to HTML...")
    converter = ExcelToHtmlConverter()
    html = converter.convert_to_html(file_path)

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

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

    # Save to file
    output_file = Path(output_path)
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html)

    print(f"\n✓ Saved HTML to: {output_file.absolute()}")
    print(f"  File size: {output_file.stat().st_size} bytes")

    # Show some stats
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, 'lxml')
    tables = soup.find_all('table')

    print(f"\nHTML Structure:")
    print(f"  Total tables: {len(tables)}")

    if tables:
        print(f"\nTable details:")
        for i, table in enumerate(tables[:10], 1):  # Show first 10
            rows = table.find_all('tr')
            print(f"    Table {i}: {len(rows)} rows")
            if len(rows) > 0:
                cells = rows[0].find_all(['th', 'td'])
                print(f"             First row: {len(cells)} cells")

        if len(tables) > 10:
            print(f"    ... and {len(tables) - 10} more tables")

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


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

    output_path = sys.argv[2] if len(sys.argv) > 2 else "converted_output.html"

    save_html_output(file_path, output_path)
