"""
Inspect drawing XML structure to understand connector format.
"""

import sys
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path

def inspect_drawing_xml(file_path: str):
    """Inspect the drawing XML to see connector structure."""
    print("=" * 80)
    print(f"INSPECTING DRAWING XML: {file_path}")
    print("=" * 80)

    with zipfile.ZipFile(file_path, "r") as zip_ref:
        # Find drawing files
        drawing_files = [
            f for f in zip_ref.namelist()
            if f.startswith("xl/drawings/drawing") and f.endswith(".xml")
        ]

        print(f"\nFound {len(drawing_files)} drawing files:")
        for df in drawing_files:
            print(f"  - {df}")

        # Inspect each drawing file
        for drawing_file in drawing_files:
            print(f"\n{'=' * 80}")
            print(f"FILE: {drawing_file}")
            print(f"{'=' * 80}")

            xml_content = zip_ref.read(drawing_file).decode('utf-8')
            root = ET.fromstring(xml_content)

            # Count different element types
            print("\nElement counts:")

            # Check for various anchor types
            two_cell_anchors = root.findall(".//{http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing}twoCellAnchor")
            one_cell_anchors = root.findall(".//{http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing}oneCellAnchor")
            abs_anchors = root.findall(".//{http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing}absoluteAnchor")

            print(f"  - twoCellAnchor: {len(two_cell_anchors)}")
            print(f"  - oneCellAnchor: {len(one_cell_anchors)}")
            print(f"  - absoluteAnchor: {len(abs_anchors)}")

            # Check for shapes and connectors
            shapes = root.findall(".//{http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing}sp")
            connectors = root.findall(".//{http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing}cxnSp")

            print(f"  - sp (shapes): {len(shapes)}")
            print(f"  - cxnSp (connectors): {len(connectors)}")

            # Show structure of first connector if found
            if connectors:
                print(f"\nFirst connector XML structure:")
                print("-" * 80)
                connector_str = ET.tostring(connectors[0], encoding='unicode')
                # Pretty print (basic)
                lines = connector_str.split('><')
                for i, line in enumerate(lines[:20]):  # First 20 elements
                    if i > 0:
                        line = '<' + line
                    if i < len(lines) - 1:
                        line = line + '>'
                    print(line)
                if len(lines) > 20:
                    print(f"... ({len(lines) - 20} more lines)")

            # Show structure of first shape if found
            if shapes:
                print(f"\nFirst shape XML structure:")
                print("-" * 80)
                shape_str = ET.tostring(shapes[0], encoding='unicode')
                # Pretty print (basic)
                lines = shape_str.split('><')
                for i, line in enumerate(lines[:20]):  # First 20 elements
                    if i > 0:
                        line = '<' + line
                    if i < len(lines) - 1:
                        line = line + '>'
                    print(line)
                if len(lines) > 20:
                    print(f"... ({len(lines) - 20} more lines)")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python inspect_drawing_xml.py <path-to-xlsx-file>")
        sys.exit(1)

    file_path = sys.argv[1]
    inspect_drawing_xml(file_path)
