"""One-off: capture the Exercises list screen (desktop + mobile, en + fr)
to replace the home-page overview screenshots in demarrage-rapide docs."""

from __future__ import annotations

import time
from pathlib import Path

from playwright.sync_api import sync_playwright

URL = "http://localhost:5199"
OUT_DIR = Path("/tmp/overview-shots")
OUT_DIR.mkdir(parents=True, exist_ok=True)

SEED_SCRIPT = """
async () => {
    const uuid = await window.__repos.settings.get('user_uuid');
    await window.__repos.exercises.create({
        title: 'Push-ups',
        description: 'Classic bodyweight push-up.',
        asymmetric: false, alternate: false, image_urls: [], video_urls: [],
        default_reps: 15, default_weight: 0, created_by: uuid
    });
    await window.__repos.exercises.create({
        title: 'Squats',
        description: 'Bodyweight squat — great for legs and glutes.',
        asymmetric: false, alternate: false, image_urls: [], video_urls: [],
        default_reps: 20, default_weight: 0, created_by: uuid
    });
    await window.__repos.exercises.create({
        title: 'Deadlift',
        description: 'Barbell deadlift — compound posterior-chain movement.',
        asymmetric: false, alternate: false, image_urls: [], video_urls: [],
        default_reps: 5, default_weight: 100, created_by: uuid
    });
}
"""


def wait_for_db(page):
    page.wait_for_function(
        "document.documentElement.getAttribute('data-db-ready') === 'true'",
        timeout=15000,
    )


def capture(browser, lang: str, width: int, height: int, name: str):
    context = browser.new_context(viewport={"width": width, "height": height})
    page = context.new_page()
    page.goto(URL)
    wait_for_db(page)
    page.evaluate(f"async () => window.__repos.settings.set('language', '{lang}')")
    page.reload()
    wait_for_db(page)

    count = page.evaluate("async () => (await window.__repos.exercises.getAll()).length")
    if count == 0:
        page.evaluate(SEED_SCRIPT)

    page.goto(f"{URL}/#/exercises")
    page.wait_for_selector('[data-testid="exercise-new-btn"]', timeout=8000)
    time.sleep(0.5)
    out_path = OUT_DIR / f"{name}.{lang}.png"
    page.screenshot(path=str(out_path), full_page=True)
    print(f"saved {out_path}")
    context.close()


def main():
    with sync_playwright() as p:
        browser = p.firefox.launch(headless=True)
        try:
            capture(browser, "en", 1920, 1080, "overview-desktop")
            capture(browser, "fr", 1920, 1080, "overview-desktop")
            capture(browser, "en", 390, 844, "overview-mobile")
            capture(browser, "fr", 390, 844, "overview-mobile")
        finally:
            browser.close()


if __name__ == "__main__":
    main()
