"""
debug_render.py — Progressive rendering tests for isolating display issues.

Type these in Excel cells to test each layer of the rendering pipeline:

  =debug_write_test()     Layer 1: Can we write to a cell at all via COM?
  =debug_batch_test()     Layer 2: Does xl_batch() work?
  =debug_grid_test()      Layer 3: Can we write a 2D grid?
  =debug_format_pong()    Layer 4: Set column/row sizes for pong display
  =debug_frame()          Layer 5: Render one static pong frame
  =debug_counter()        Layer 6: Animated counter (1 cell, 1Hz)
  =debug_stop()           Stop any running animation
"""

import shortcut_xl
from shortcut_xl import xl_func, xl_log

_counter_running = False


# === Layer 1: Basic COM write ===


@xl_func
def debug_write_test():
    """Write a value to Z1 via xl_app() COM. Simplest possible test."""
    try:

        def _do(app):
            app.ActiveSheet.Range('Z1').Value = 'WRITE_OK'

        shortcut_xl.xl_batch(_do)
        return "Wrote 'WRITE_OK' to Z1 — check Z1"
    except Exception as e:
        xl_log(f'debug_write_test FAILED: {e}')
        return f'FAILED: {e}'


# === Layer 2: xl_batch with ScreenUpdating toggle ===


@xl_func
def debug_batch_test():
    """Write 3 cells in one batch. Tests ScreenUpdating toggle + PumpWaitingMessages."""
    try:

        def _do(app):
            sheet = app.ActiveSheet
            sheet.Range('Z1').Value = 'BATCH'
            sheet.Range('Z2').Value = 'TEST'
            sheet.Range('Z3').Value = 'OK'

        shortcut_xl.xl_batch(_do)
        return 'Wrote Z1:Z3 — check those cells'
    except Exception as e:
        xl_log(f'debug_batch_test FAILED: {e}')
        return f'FAILED: {e}'


# === Layer 3: 2D grid write via Resize().Value ===


@xl_func
def debug_grid_test():
    """Write a small 5x5 grid using the same Resize().Value pattern as pong."""
    try:
        grid = []
        for r in range(5):
            row = []
            for c in range(5):
                if r == 0 or r == 4 or c == 0 or c == 4:
                    row.append('#')  # border
                elif r == 2 and c == 2:
                    row.append('X')  # center
                else:
                    row.append('')  # empty (same as pong does)
            grid.append(row)

        def _do(app):
            sheet = app.ActiveSheet
            sheet.Range('Z5:AD9').Value = grid

        shortcut_xl.xl_batch(_do)
        xl_log(f'debug_grid_test: wrote 5x5 grid to Z5:AD9, data={grid}')
        return 'Wrote 5x5 grid to Z5:AD9 — check those cells'
    except Exception as e:
        xl_log(f'debug_grid_test FAILED: {e}')
        return f'FAILED: {e}'


# === Layer 3b: Grid with tuples (test COM conversion) ===


@xl_func
def debug_grid_tuple_test():
    """Same as grid_test but converts to tuple-of-tuples for COM.
    If this works but debug_grid_test doesn't, it's a list-vs-tuple issue."""
    try:
        grid = []
        for r in range(5):
            row = []
            for c in range(5):
                if r == 0 or r == 4 or c == 0 or c == 4:
                    row.append('#')
                elif r == 2 and c == 2:
                    row.append('X')
                else:
                    row.append('')
            grid.append(tuple(row))
        grid = tuple(grid)

        def _do(app):
            sheet = app.ActiveSheet
            sheet.Range('Z5:AD9').Value = grid

        shortcut_xl.xl_batch(_do)
        xl_log('debug_grid_tuple_test: wrote tuple grid to Z5:AD9')
        return 'Wrote tuple-of-tuples 5x5 to Z5:AD9'
    except Exception as e:
        xl_log(f'debug_grid_tuple_test FAILED: {e}')
        return f'FAILED: {e}'


# === Layer 4: Format cells for pong display ===


@xl_func
def debug_format_pong():
    """Set up column widths and row heights so pong grid looks right.
    This is what pong.py is missing — without it, the grid is spread across
    the entire screen and looks like nothing."""
    try:

        def _do(app):
            sheet = app.ActiveSheet
            # Columns A-AD (1-30): narrow width for character grid
            cols = sheet.Range('A:AD')
            cols.ColumnWidth = 2.0
            cols.HorizontalAlignment = -4108  # xlCenter

            # Rows 3-22 (pong grid area): compact height
            rows = sheet.Range('3:22')
            rows.RowHeight = 15

            # Monospace font for the grid
            grid_range = sheet.Range('A3:AD22')
            grid_range.Font.Name = 'Consolas'
            grid_range.Font.Size = 11

            # Scoreboard formatting
            sheet.Range('A1').Font.Name = 'Consolas'
            sheet.Range('A1').Font.Size = 14
            sheet.Range('A1').Font.Bold = True

        shortcut_xl.xl_batch(_do)
        return 'Formatted A:AD for pong display'
    except Exception as e:
        xl_log(f'debug_format_pong FAILED: {e}')
        return f'FAILED: {e}'


# === Layer 5: Static pong frame ===


@xl_func
def debug_frame():
    """Render exactly one pong frame. No animation, no schedule_call.
    If this shows up, the rendering works and the issue is in the animation loop."""
    try:
        WIDTH, HEIGHT, PADDLE_H = 30, 20, 4
        grid = []
        ball_x, ball_y = 15, 10
        paddle_l, paddle_r = 8, 8

        for r in range(HEIGHT):
            row = []
            for c in range(WIDTH):
                ch = ''
                if c == 0 and paddle_l <= r < paddle_l + PADDLE_H:
                    ch = chr(9608)  # full block
                elif c == WIDTH - 1 and paddle_r <= r < paddle_r + PADDLE_H:
                    ch = chr(9608)
                elif r == ball_y and c == ball_x:
                    ch = chr(9679)  # black circle
                elif c == WIDTH // 2 and r % 2 == 0:
                    ch = chr(9474)  # light vertical
                row.append(ch)
            grid.append(row)

        def _do(app):
            sheet = app.ActiveSheet
            sheet.Range('A3:AD22').Value = grid
            sheet.Range('A1').Value = 'PONG   0  :  0'
            sheet.Range('A2').Value = 'Static frame test'

        shortcut_xl.xl_batch(_do)
        xl_log('debug_frame: wrote static pong frame')
        return 'Wrote static pong frame to A3:AD22'
    except Exception as e:
        xl_log(f'debug_frame FAILED: {e}')
        return f'FAILED: {e}'


# === Layer 5b: Static frame with ASCII (no Unicode) ===


@xl_func
def debug_frame_ascii():
    """Same as debug_frame but uses ASCII chars only.
    If this renders but debug_frame doesn't, it's a Unicode/font issue."""
    try:
        WIDTH, HEIGHT, PADDLE_H = 30, 20, 4
        grid = []
        ball_x, ball_y = 15, 10
        paddle_l, paddle_r = 8, 8

        for r in range(HEIGHT):
            row = []
            for c in range(WIDTH):
                ch = '.'  # visible empty (not "")
                if (
                    c == 0
                    and paddle_l <= r < paddle_l + PADDLE_H
                    or c == WIDTH - 1
                    and paddle_r <= r < paddle_r + PADDLE_H
                ):
                    ch = '|'
                elif r == ball_y and c == ball_x:
                    ch = 'O'
                elif c == WIDTH // 2 and r % 2 == 0:
                    ch = ':'
                row.append(ch)
            grid.append(row)

        def _do(app):
            sheet = app.ActiveSheet
            sheet.Range('A3:AD22').Value = grid
            sheet.Range('A1').Value = 'PONG   0  :  0'
            sheet.Range('A2').Value = 'Static ASCII frame test'

        shortcut_xl.xl_batch(_do)
        xl_log('debug_frame_ascii: wrote ASCII pong frame')
        return 'Wrote ASCII pong frame to A3:AD22'
    except Exception as e:
        xl_log(f'debug_frame_ascii FAILED: {e}')
        return f'FAILED: {e}'


# === Layer 6: Animated counter (simplest animation) ===


@xl_func
def debug_counter():
    """Increment a single cell once per second. Simplest animation test.
    If this works, schedule_call + xl_batch animation pipeline is fine."""
    global _counter_running
    if _counter_running:
        return 'Already running! =debug_stop() first'

    _counter_running = True
    _count = [0]

    def _tick():
        if not _counter_running:
            return
        _count[0] += 1
        xl_log(f'debug_counter tick: {_count[0]}')
        try:

            def _do(app):
                app.ActiveSheet.Range('Z1').Value = f'Count: {_count[0]}'

            shortcut_xl.xl_batch(_do)
        except Exception as e:
            xl_log(f'debug_counter error: {e}')

        if _counter_running and _count[0] < 30:
            shortcut_xl.schedule_call(_tick, 1.0)

    shortcut_xl.schedule_call(_tick, 0.1)
    return 'Counting in Z1 (1/sec, 30 max)'


@xl_func
def debug_stop():
    """Stop the debug counter."""
    global _counter_running
    _counter_running = False
    return 'Stopped'
