# apps/aroflo_connector_app/ui_automation/commands/timesheet_delete.py
from __future__ import annotations

from playwright.sync_api import sync_playwright

from ..core.browser import launch_browser_context
from ..core.artifacts import create_run_dir, shot
from ..auth.session import ensure_logged_in
from ..flows import timesheet_nav, timesheet_select_date
from ..flows.timesheet_delete import DeleteRule
from ..flows import timesheet_delete


def cmd_timesheet_delete(cfg) -> int:
    if not cfg.state_file.exists():
        raise SystemExit(f"storageState not found: {cfg.state_file}. Run bootstrap first.")

    run_dir = create_run_dir(cfg, "timesheet-delete")

    # Flags desde cfg (vienen del runner argparse)
    delete_all = bool(getattr(cfg, "delete_all", False))
    include_protected = bool(getattr(cfg, "include_protected", False))

    # Fecha objetivo (YYYY-MM-DD)
    target_date = getattr(cfg, "timesheet_date", "2026-01-08")

    # Defaults (modo regla). En delete_all esto queda “de adorno”, pero no estorba.
    rule = DeleteRule(
        overheads_to_delete=[
            "Admin Duties",
            "Admin Duties - Telecommunications",
        ],
        protected_overheads=[
            "Lunch Break - Unpaid",
        ],
        match_mode="exact",
        delete_all=delete_all,
        include_protected=include_protected,
    )

    with sync_playwright() as p:
        browser, context = launch_browser_context(p, cfg, storage_state=str(cfg.state_file))
        page = context.new_page()

        try:
            ensure_logged_in(page, cfg, run_dir, mfa_code="", allow_mfa=False)

            # Ir a Timesheets
            timesheet_nav.run(page, cfg, run_dir)

            # Seleccionar la fecha ANTES de borrar
            timesheet_select_date.run(
                page,
                cfg,
                run_dir,
                target_date=target_date,
            )

            # Borrar (hours -> 0) y verificar
            timesheet_delete.run(page, cfg, run_dir, rule=rule)

            shot(page, run_dir, "ok")
            context.storage_state(path=str(cfg.state_file))

        except Exception:
            shot(page, run_dir, "99-error")
            raise
        finally:
            try:
                context.close()
            except Exception:
                pass
            try:
                browser.close()
            except Exception:
                pass

    print("[UI] timesheet-delete OK")
    print(f"[UI] Date: {target_date}")
    print(f"[UI] delete_all={delete_all} include_protected={include_protected}")
    print(f"[UI] Artifacts: {run_dir}")
    return 0
