#!/usr/bin/env python3
"""Manual test script for parsing Excel files and splitting tables into separate markdown files.

This script:
1. Parses an Excel file using ExcelParserService
2. Splits the resulting markdown into individual tables
3. Saves each table as a separate markdown file in ./tmp/tables/
"""

import re
import sys
from datetime import datetime
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from src.extraction.excel_parser import get_excel_parser_service


def split_markdown_tables(markdown_content: str) -> list[dict[str, str]]:
    """Split markdown content into individual tables.

    Args:
        markdown_content: Full markdown content with multiple tables

    Returns:
        List of dicts with 'title' and 'content' for each table
    """
    tables = []

    # Split by markdown table pattern - matches tables that start with |
    # Using regex to find table blocks
    lines = markdown_content.split('\n')

    current_table = []
    table_started = False
    table_number = 1

    for i, line in enumerate(lines):
        stripped = line.strip()

        # Check if this is a table line (starts with |)
        if stripped.startswith('|'):
            if not table_started:
                table_started = True
            current_table.append(line)
        else:
            # If we were in a table and hit a non-table line, save the table
            if table_started and current_table:
                table_content = '\n'.join(current_table)

                # Try to find a title in the previous few lines
                title = f"Table {table_number}"
                for j in range(max(0, i - len(current_table) - 5), i - len(current_table)):
                    prev_line = lines[j].strip()
                    if prev_line and not prev_line.startswith('|') and not prev_line.startswith('#'):
                        title = prev_line[:100]  # Use first 100 chars as title
                        break

                tables.append({
                    'title': title,
                    'content': table_content,
                    'number': table_number
                })

                table_number += 1
                current_table = []
                table_started = False

    # Don't forget the last table if the file ends with a table
    if table_started and current_table:
        table_content = '\n'.join(current_table)
        tables.append({
            'title': f"Table {table_number}",
            'content': table_content,
            'number': table_number
        })

    return tables


def save_tables_to_files(tables: list[dict[str, str]], output_dir: Path, base_filename: str):
    """Save each table to a separate markdown file.

    Args:
        tables: List of table dicts
        output_dir: Directory to save files to
        base_filename: Base name for the output files
    """
    output_dir.mkdir(parents=True, exist_ok=True)

    for table in tables:
        # Create filename from table number
        filename = f"{base_filename}_table_{table['number']:03d}.md"
        filepath = output_dir / filename

        # Create markdown content with title
        content = f"# {table['title']}\n\n{table['content']}\n"

        # Save to file
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)

        print(f"  ✓ Saved table {table['number']}: {filepath.name} ({len(table['content'])} chars)")


def main():
    """Run the Excel parsing and table splitting test."""

    # Test file - same as test_conversion_manual.py (using filesystem-encoded path)
    default_test_file = "CustomerDocument/уВ╖уВ╣уГЖуГауГХуГнуГ╝хЫ│/01.04.02.01.04.04_уВ╖уВ╣уГЖуГауГХуГнуГ╝хЫ│ц│ищЗИф╕Ашжзя╝ИцЬмчФ│ш╛╝я╝Их╗Гцнвя╝Йя╝Й.xlsm"

    print("=" * 70)
    print("EXCEL PARSING & TABLE SPLITTING TEST")
    print("=" * 70)
    print(f"\nTest file: {default_test_file}")

    test_file = Path(default_test_file)

    if not test_file.exists():
        print(f"Error: File not found: {test_file}")
        return

    print("=" * 70)

    # Read file content
    print(f"\n[1/5] Reading file...")
    with open(test_file, 'rb') as f:
        file_content = f.read()

    file_size_mb = len(file_content) / (1024 * 1024)
    print(f"  File size: {len(file_content):,} bytes ({file_size_mb:.2f} MB)")
    print(f"  Extension: {test_file.suffix}")

    # Get parser service
    print(f"\n[2/5] Initializing Excel parser service...")
    parser_service = get_excel_parser_service()
    print(f"  ✓ Parser service initialized")

    # Parse the file
    print(f"\n[3/5] Parsing Excel file to markdown...")
    print("=" * 70)

    try:
        import time
        start_time = time.time()

        markdown_content = parser_service.parse_excel_file(
            file_content=file_content,
            original_filename=test_file.name,
        )

        end_time = time.time()
        duration_ms = (end_time - start_time) * 1000

        print("=" * 70)
        print(f"\n[4/5] Parsing complete!")
        print(f"  Duration: {duration_ms:.0f}ms ({duration_ms/1000:.2f}s)")
        print(f"  Output size: {len(markdown_content):,} characters")

        # Split tables
        print(f"\n[5/5] Splitting tables and saving to files...")
        tables = split_markdown_tables(markdown_content)
        print(f"  Found {len(tables)} tables")

        # Create output directory with timestamp
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        base_filename = test_file.stem
        output_dir = Path("./tmp/tables") / f"{timestamp}_{base_filename}"

        # Save tables
        save_tables_to_files(tables, output_dir, base_filename)

        print(f"\n  ✓ All tables saved to: {output_dir}")

        # Display summary
        print("\n" + "=" * 70)
        print("TABLE SUMMARY")
        print("=" * 70)
        for i, table in enumerate(tables[:10], 1):  # Show first 10
            print(f"{i:3d}. {table['title'][:60]:<60} ({len(table['content']):>6} chars)")

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

        print("\n" + "=" * 70)
        print("Test completed successfully!")
        print("=" * 70)

    except Exception as e:
        print("\n" + "=" * 70)
        print("PARSING FAILED!")
        print("=" * 70)
        print(f"\nError: {e}")

        import traceback
        print("\nFull traceback:")
        traceback.print_exc()


if __name__ == "__main__":
    main()
