# apps/aroflo_connector_app/ui_automation/commands/timesheet_create.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_create
from ..flows import timesheet_select_date
from ..flows.timesheet_create import NewRowSpec


def cmd_timesheet_create(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-create")

    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 timesheet
            timesheet_nav.run(page, cfg, run_dir)

            timesheet_select_date.run(
                page,
                cfg,
                run_dir,
                target_date=getattr(cfg, "timesheet_date", "2026-01-08"),
            )
            rows = None
            if getattr(cfg, "timesheet_rows", None):
                rows = [
                    NewRowSpec(
                        hours=r["hours"],
                        overhead=r["overhead"],
                        note=(r.get("note") or None),
                        worktype_label=r.get("worktype", "NT"),
                        tracking_label=r.get("tracking", "ADMIN"),
                    )
                    for r in cfg.timesheet_rows
                ]

            # crear (multi-fila) + guardar
            # Nota: el flujo define defaults (3 filas) si no se pasan rows
            timesheet_create.run(page, cfg, run_dir, rows=rows)

            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-create OK")
    print(f"[UI] Artifacts: {run_dir}")
    return 0
