"""Playwright test script to verify zero occlusion on drawing takeoff dashboard."""

from __future__ import annotations

import time
from pathlib import Path

from playwright.sync_api import sync_playwright

vault = Path("storage/screenshots")
vault.mkdir(parents=True, exist_ok=True)
screenshot_path = vault / "drawing_takeoff_zero_occlusion_test.png"

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context(viewport={"width": 1440, "height": 900})

    # Ensure localStorage auth state exists on all pages
    context.add_init_script("""
        localStorage.setItem('dscons_jwt_token', 'mock_dev_token');
        localStorage.setItem('dscons_user', JSON.stringify({
            id: 'admin-1',
            email: 'admin@dscons.vn',
            full_name: 'Giám Đốc Kỹ Thuật',
            role: 'director',
            is_active: true
        }));
    """)

    page = context.new_page()

    # Navigate to drawing takeoff dashboard
    page.goto(
        "http://127.0.0.1:8000/dashboard/drawing-takeoff", wait_until="networkidle"
    )
    time.sleep(1.5)

    # Inspect bounding boxes
    sidebar = page.locator("#erp-sidebar")
    sidebar_box = sidebar.bounding_box()

    main_layout = page.locator(".erp-main-layout")
    layout_box = main_layout.bounding_box()

    page_container = page.locator(".page-container")
    container_box = page_container.bounding_box()

    topbar = page.locator(".erp-topbar")
    topbar_box = topbar.bounding_box()

    print("=== THONG SO TOA DO THUC TE TREN TRINH DUYET ===")
    print(
        f"1. Sidebar Bounding Box     : x={sidebar_box['x']:.1f}, y={sidebar_box['y']:.1f}, w={sidebar_box['width']:.1f}, h={sidebar_box['height']:.1f}"
    )
    print(
        f"2. Main Layout Bounding Box : x={layout_box['x']:.1f}, y={layout_box['y']:.1f}, w={layout_box['width']:.1f}, h={layout_box['height']:.1f}"
    )
    print(
        f"3. Topbar Bounding Box      : x={topbar_box['x']:.1f}, y={topbar_box['y']:.1f}, w={topbar_box['width']:.1f}, h={topbar_box['height']:.1f}"
    )
    print(
        f"4. Page Container Box       : x={container_box['x']:.1f}, y={container_box['y']:.1f}, w={container_box['width']:.1f}, h={container_box['height']:.1f}"
    )

    # Verify Zero Occlusion: Layout X must equal Sidebar Width
    is_occluded = layout_box["x"] < (sidebar_box["width"] - 2)
    result_text = (
        "BI DE LOI!" if is_occluded else "DAT CHUAN 100% (ZERO OCCLUSION - KHONG BI DE)"
    )
    print(f"\n5. KET QUA KIEM TRA: {result_text}")
    assert not is_occluded, "Loi: Noi dung van bi de len Menu/Sidebar!"

    page.screenshot(path=str(screenshot_path), full_page=False)
    print(f"6. Da luu anh chup man hinh minh chung: {screenshot_path}")

    browser.close()
