"""Screenshots aller App-Reiter erzeugen (Doku/Review).

Rendert jede Seite der PilotNG-App in einem unsichtbaren Fenster und
fotografiert sie per PrintWindow — funktioniert auch ohne sichtbaren
Desktop (z. B. via SSH). Schreibt PNGs nach docs/screenshots/.

Aufruf: python scripts/screenshot_pages.py
"""
import sys
import time
from pathlib import Path

# Repo-root zuerst: im venv liegt eine alte installierte src-Kopie,
# die das Skript sonst faengt (sys.path[0] waere nur scripts/).
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

OUT_DIR = Path('docs/screenshots')

PAGES = [
    ('Dashboard', 'dashboard'),
    ('Cave Bot', 'cavebot'),
    ('Healing', 'healing'),
    ('Kombos', 'kombos'),
    ('Inventar', 'inventar'),
    ('Tod', 'tod'),
    ('Einstellungen', 'einstellungen'),
    ('Konto', 'konto'),
]


def captureWindow(hwnd, path):
    import ctypes

    import win32gui
    import win32ui
    from PIL import Image

    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    width, height = right - left, bottom - top
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    bitmap = win32ui.CreateBitmap()
    bitmap.CreateCompatibleBitmap(mfcDC, width, height)
    saveDC.SelectObject(bitmap)
    # Fenster zum Neuzeichnen zwingen, sonst bleibt der DC schwarz.
    RDW_INVALIDATE = 0x1
    RDW_ALLCHILDREN = 0x80
    RDW_UPDATENOW = 0x100
    ctypes.windll.user32.RedrawWindow(
        hwnd, None, None, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW)
    time.sleep(0.3)
    # 0 = WM_PRINT an alle Kinder, 2 = PW_RENDERFULLCONTENT
    ok = ctypes.windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0)
    info = bitmap.GetInfo()
    bits = bitmap.GetBitmapBits(True)
    image = Image.frombuffer(
        'RGB', (info['bmWidth'], info['bmHeight']),
        bits, 'raw', 'BGRX', 0, 1)
    if image.convert('L').getextrema() == (0, 0) or not ok:
        # Fallback: Bildschirmbereich des Fensters abfotografieren.
        from PIL import ImageGrab
        image = ImageGrab.grab(bbox=(left, top, right, bottom))
    image.save(path)
    win32gui.DeleteObject(bitmap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)


def moveToSecondMonitor(app):
    """Fenster auf den zweiten Bildschirm schieben (falls vorhanden)."""
    try:
        import win32api
        for monitor in win32api.EnumDisplayMonitors():
            x1, y1, _x2, _y2 = monitor[2]
            if (x1, y1) != (0, 0):  # nicht der Primaer-Monitor
                app.geometry(f'+{x1 + 40}+{y1 + 40}')
                return True
    except Exception:
        pass
    return False


def main():
    import win32gui

    from src.gameplay.context import context
    from src.ui.application import Application
    from src.ui.context import Context

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    app = Application(Context(context))
    app.update()
    moveToSecondMonitor(app)
    app.update()
    time.sleep(1)
    app.lift()
    app.attributes('-topmost', True)
    hwnd = win32gui.GetAncestor(app.winfo_id(), 2)  # GA_ROOT
    for name, slug in PAGES:
        try:
            app.showPage(name)
            app.lift()
            app.update()
            time.sleep(1.5)  # erste _refresh-Runde abwarten
            app.update()
            target = OUT_DIR / f'{slug}.png'
            captureWindow(hwnd, target)
            print(f'OK {name} -> {target}')
        except Exception:  # noqa: BLE001 — Report statt Abbruch
            import traceback
            print(f'FEHLER {name}:')
            traceback.print_exc()
    # Design-Nachweise: Akzent-Wechsel (Violett) und Hell-Modus.
    try:
        saved = app.context.getUiTheme()
        savedMode = app.context.getUiMode()
        app.applyTheme('violett')
        app.showPage('Dashboard', animate=False)
        app.update()
        time.sleep(1)
        app.update()
        captureWindow(hwnd, OUT_DIR / 'theme-violett.png')
        print('OK Theme violett -> docs\\screenshots\\theme-violett.png')
        app.context.setUiMode('hell')
        app.applyDesign()
        app.showPage('Dashboard', animate=False)
        app.update()
        time.sleep(1)
        app.update()
        captureWindow(hwnd, OUT_DIR / 'theme-hell.png')
        print('OK Modus hell -> docs\\screenshots\\theme-hell.png')
        app.context.setUiTheme(saved)
        app.context.setUiMode(savedMode)
        app.applyDesign()
    except Exception:  # noqa: BLE001
        import traceback
        print('FEHLER Theme-Demo:')
        traceback.print_exc()
    app.destroy()
    (OUT_DIR / '.done').write_text(str(time.time()), encoding='utf-8')


if __name__ == '__main__':
    main()
