#!/usr/bin/env python3
"""Debug image extraction from Excel sheets."""

import sys
import subprocess
import tempfile
from pathlib import Path

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

from openpyxl import load_workbook
from openpyxl.drawing.image import Image as OpenpyxlImage


def convert_xls_to_xlsx(xls_path: str) -> str:
    """Convert .xls to .xlsx using LibreOffice."""
    temp_dir = tempfile.mkdtemp()

    result = subprocess.run([
        '/Applications/LibreOffice.app/Contents/MacOS/soffice',
        '--headless',
        '--convert-to', 'xlsx',
        '--outdir', temp_dir,
        xls_path
    ], capture_output=True, text=True, timeout=60)

    xlsx_files = list(Path(temp_dir).glob('*.xlsx'))
    return str(xlsx_files[0]) if xlsx_files else None


def extract_images_from_sheet(xlsx_path: str, sheet_name: str):
    """Extract all images from a specific sheet."""
    wb = load_workbook(xlsx_path, data_only=True)

    if sheet_name not in wb.sheetnames:
        print(f"Sheet '{sheet_name}' not found!")
        return

    ws = wb[sheet_name]

    print(f"\n{'='*80}")
    print(f"SHEET: {sheet_name}")
    print(f"{'='*80}\n")

    # Check if sheet has _images attribute
    if hasattr(ws, '_images') and ws._images:
        print(f"Found {len(ws._images)} images in sheet._images:\n")

        for idx, img in enumerate(ws._images):
            print(f"Image {idx + 1}:")
            print(f"  Type: {type(img)}")
            print(f"  Format: {getattr(img, 'format', 'unknown')}")

            # Check anchor information
            if hasattr(img, 'anchor'):
                anchor = img.anchor
                print(f"  Anchor type: {type(anchor)}")

                if hasattr(anchor, '_from'):
                    from_cell = anchor._from
                    print(f"  From cell: {from_cell}")
                    if hasattr(from_cell, 'col') and hasattr(from_cell, 'row'):
                        print(f"    Column: {from_cell.col}, Row: {from_cell.row}")

                if hasattr(anchor, 'col'):
                    print(f"  Anchor col: {anchor.col}")
                if hasattr(anchor, 'row'):
                    print(f"  Anchor row: {anchor.row}")

            # Check if it's a TwoCellAnchor
            if hasattr(img.anchor, '__class__'):
                print(f"  Anchor class: {img.anchor.__class__.__name__}")

            print()
    else:
        print("No images found in sheet._images\n")

    # Also check for embedded images in cells
    print("Checking for images in worksheet._images or drawing parts...")

    if hasattr(ws, '_drawing'):
        print(f"  Sheet has _drawing: {ws._drawing}")

    if hasattr(ws, '_charts'):
        print(f"  Sheet has _charts: {len(ws._charts) if ws._charts else 0}")

    wb.close()


def main(file_path: str, sheet_name: str):
    """Debug image extraction."""

    print(f"File: {file_path}")
    print(f"Target sheet: {sheet_name}")

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

    # Extract images
    extract_images_from_sheet(xlsx_path, sheet_name)

    # Also list all sheets
    print(f"\n{'='*80}")
    print("ALL SHEETS:")
    print(f"{'='*80}\n")

    wb = load_workbook(xlsx_path, data_only=True)
    for sheet_name in wb.sheetnames:
        ws = wb[sheet_name]
        img_count = len(ws._images) if hasattr(ws, '_images') and ws._images else 0
        print(f"  {sheet_name}: {img_count} images")
    wb.close()


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python debug_image_extraction.py <excel_file> <sheet_name>")
        sys.exit(1)

    main(sys.argv[1], sys.argv[2])
