# /apps/aroflo_connector_app/ui_automation/runner.py
import argparse
from pathlib import Path
from dotenv import load_dotenv

from .core.config import build_config

# Cargar SIEMPRE el .env del root del core (flask_server/.env)
CORE_ROOT = Path(__file__).resolve().parents[3]
load_dotenv(CORE_ROOT / ".env")


def build_parser():
    p = argparse.ArgumentParser("AroFlo UI Automation")
    p.add_argument("--base-url")
    p.add_argument("--username")
    p.add_argument("--password")
    p.add_argument("--state-file")
    p.add_argument("--artifacts-dir")
    p.add_argument("--headless", action=argparse.BooleanOptionalAction, default=None)
    p.add_argument("--slow-mo-ms", type=int)
    p.add_argument("--step", action="store_true")
    p.add_argument("--pause-on-mfa", action="store_true")
    p.add_argument("--mfa-code", default="")

    # global flags
    p.add_argument("--timesheet-date", default="", help="Target date for Daily Timesheet in YYYY-MM-DD")
    p.add_argument("--timesheet-bu", default="", help="Business Unit name to select in AroFlo (e.g. 'Utility Solutions Group')")
    p.add_argument("--delete-all", action="store_true", help="Delete ALL existing entries in the selected date (hours -> 0)")
    p.add_argument("--include-protected", action="store_true", help="Also delete protected rows like Lunch Break (use with --delete-all)")
    p.add_argument("--row", action="append", default=[], help="Timesheet row spec. Repeatable.")
    p.add_argument("--timesheet-user-id", default="", help="AroFlo User ID to select in Timesheets (preferred, unique)")
    p.add_argument("--timesheet-user-name", default="", help="AroFlo User full name to select in Timesheets (fallback, non-unique)")
    p.add_argument("--user-email", default="", help="Email del usuario a buscar en Users (ej: cpenuela@usg.com.au)",)
    p.add_argument("--file", action="append", default=[], help="Ruta de archivo a adjuntar en el perfil del usuario (repeatable). Ej: --file /path/a.pdf --file /path/b.jpg",)
    p.add_argument("--comment", action="append", default=[], help="Comment para el documento (repeatable, se mapea con --file por índice).",)
    p.add_argument("--filter", action="append", default=[], help="Filter para el documento (repeatable, se mapea con --file por índice). "
         "Opciones: Internal Only | Internal Admin Only (Legacy) | "
         "Internal Admin and Manager Only (Legacy) | Show Client | Show Contractor | Show All",)
    # NUEVO (recomendado): tripleta repetible
    p.add_argument("--doc", action="append", default=[], help=(
        'Tripleta repetible. Ej: '
        '--doc "file=/path/a.pdf;comment=uno;filter=Internal Only" '
        '--doc "file=/path/b.jpg;comment=dos;filter=Show Contractor"'),
    )


    sub = p.add_subparsers(dest="cmd", required=True)
    sub.add_parser("bootstrap")
    sub.add_parser("smoke")
    sub.add_parser("timesheet-nav", help="Navigate: Dashboard -> Manage -> Timesheets")
    sub.add_parser("timesheet-create", help="Create a timesheet entry via UI automation")
    sub.add_parser("timesheet-delete", help="Delete timesheet entries (hours=0) via UI automation")

    # NUEVO
    sub.add_parser("users-nav", help="Navigate: Dashboard -> Manage -> Users")
    sub.add_parser("users-upload-docs", help="Users: open profile by email and upload 1..N documents")


    return p


def main(argv=None):
    args = build_parser().parse_args(argv)
    cfg = build_config(args)

    if args.cmd == "bootstrap":
        from .commands.bootstrap import cmd_bootstrap
        return cmd_bootstrap(cfg, args.mfa_code)

    if args.cmd == "smoke":
        from .commands.smoke import cmd_smoke
        return cmd_smoke(cfg)

    if args.cmd == "timesheet-nav":
        from .commands.timesheet_nav import cmd_timesheet_nav
        return cmd_timesheet_nav(cfg)

    if args.cmd == "timesheet-create":
        from .commands.timesheet_create import cmd_timesheet_create
        return cmd_timesheet_create(cfg)

    if args.cmd == "timesheet-delete":
        from .commands.timesheet_delete import cmd_timesheet_delete
        return cmd_timesheet_delete(cfg)

    if args.cmd == "users-nav":
        from .commands.users_nav import cmd_users_nav
        return cmd_users_nav(cfg)
    
    if args.cmd == "users-upload-docs":
        from .commands.users_upload_documents import cmd_users_upload_documents
        return cmd_users_upload_documents(cfg, args.mfa_code)


    raise SystemExit("Unknown command")


if __name__ == "__main__":
    raise SystemExit(main())
