#!/usr/bin/env python3
"""Save preprocessed Excel file for debugging."""

import sys
import os
from pathlib import Path
from shutil import copy2

from src.extraction_v2.excel_to_html_converter import ExcelToHtmlConverter


def save_preprocessed_excel(input_path: str, output_path: str = None):
    """Preprocess Excel and save to file for debugging."""

    print("=" * 80)
    print("SAVE PREPROCESSED EXCEL")
    print("=" * 80)
    print(f"\nInput file: {input_path}")

    input_file = Path(input_path)
    if not input_file.exists():
        print(f"❌ Error: File not found: {input_path}")
        return

    # Default output path
    if output_path is None:
        output_path = f"preprocessed_{input_file.name}"

    print(f"Output file: {output_path}")

    # Run preprocessing
    print("\n1. Running preprocessing (this may take a while)...")
    converter = ExcelToHtmlConverter()

    try:
        # Convert to .xlsx first if needed
        _, ext = os.path.splitext(input_path)
        ext_lower = ext.lower()

        if ext_lower in ['.xls', '.xlsm']:
            print(f"   Converting {ext_lower} to .xlsx first...")
            temp_xlsx_path = converter._convert_to_xlsx_via_libreoffice(input_path)
            if temp_xlsx_path is None:
                print(f"❌ Error: LibreOffice conversion failed")
                return
            file_to_preprocess = temp_xlsx_path
        else:
            file_to_preprocess = input_path

        # Run preprocessing with border detection
        print("   Running preprocessing pipeline...")
        preprocessed_path = converter._preprocess_with_border_detection(file_to_preprocess)

        if preprocessed_path is None:
            print(f"❌ Error: Preprocessing failed")
            return

        print(f"   ✓ Preprocessing complete")
        print(f"   Temp file: {preprocessed_path}")

        # Copy to desired output location
        print(f"\n2. Copying preprocessed file to: {output_path}")
        output_file = Path(output_path)
        copy2(preprocessed_path, output_file)

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

        # Show some info about what changed
        original_size = input_file.stat().st_size
        preprocessed_size = output_file.stat().st_size
        size_diff = preprocessed_size - original_size

        print(f"\nFile size comparison:")
        print(f"  Original:     {original_size:,} bytes")
        print(f"  Preprocessed: {preprocessed_size:,} bytes")
        print(f"  Difference:   {size_diff:+,} bytes ({size_diff/original_size*100:+.1f}%)")

        print("\nYou can now open the preprocessed file in Excel to see:")
        print("  - Separator rows inserted by BorderTableDetector")
        print("  - Image descriptions applied to cells")
        print("  - Shape annotations embedded")
        print("  - Comment markers added")
        print("  - How tables were split or modified")

    except Exception as e:
        print(f"\n❌ Error during preprocessing: {e}")
        import traceback
        traceback.print_exc()
        return

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


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python save_preprocessed_excel.py <excel_file_path> [output_path]")
        print("\nExample:")
        print('  python save_preprocessed_excel.py "input.xlsx" "preprocessed_output.xlsx"')
        sys.exit(1)

    input_path = sys.argv[1]
    output_path = sys.argv[2] if len(sys.argv) > 2 else None

    save_preprocessed_excel(input_path, output_path)
