"""Provisionamento staff VM123 ao activar utilizador Desk."""

from __future__ import annotations

import logging
from typing import Any

from app.vm123 import foss_client, odoo_client, openpanel_client, provision_store
from app.vm123.role_map import PROVISIONABLE_DESK_ROLES

log = logging.getLogger(__name__)


def provision_desk_user(
    conn,
    *,
    desk_username: str,
    desk_role: str,
    display_name: str,
    email: str,
) -> dict[str, Any]:
    """Tenta FOSS + Odoo; regista resultado (mesmo parcial) em vm123_identity_map."""
    if desk_role not in PROVISIONABLE_DESK_ROLES:
        return {"skipped": True, "reason": f"role {desk_role} sem provisionamento automático"}

    result: dict[str, Any] = {"desk_username": desk_username, "desk_role": desk_role, "steps": {}}

    try:
        result["steps"]["foss"] = foss_client.create_staff(
            email=email, name=display_name or email, desk_role=desk_role
        )
    except Exception as exc:
        log.warning("FOSS provision failed for %s: %s", email, exc)
        result["steps"]["foss"] = {"error": str(exc)}

    try:
        result["steps"]["odoo"] = odoo_client.upsert_internal_user(
            email=email, name=display_name or email, desk_role=desk_role
        )
    except Exception as exc:
        log.warning("Odoo provision failed for %s: %s", email, exc)
        result["steps"]["odoo"] = {"error": str(exc)}

    if desk_role in ("sales_admin", "sales_support", "content_editor", "seo", "marketing"):
        result["steps"]["openpanel"] = {
            "note": "OpenPanel staff não provisionado no MVP — autologin cliente via bridge Fase 3+",
            "bridge": openpanel_client.bridge_configured(),
        }

    foss_id = None
    foss_step = result["steps"].get("foss") or {}
    if foss_step.get("foss_staff_id"):
        foss_id = str(foss_step["foss_staff_id"])

    odoo_uid = None
    odoo_step = result["steps"].get("odoo") or {}
    if odoo_step.get("odoo_uid"):
        odoo_uid = int(odoo_step["odoo_uid"])

    provision_store.upsert_map(
        conn,
        desk_username=desk_username,
        desk_role=desk_role,
        foss_staff_id=foss_id,
        odoo_uid=odoo_uid,
        provision=result,
    )
    result["ok"] = not any(
        isinstance(step, dict) and step.get("error") for step in result["steps"].values()
    )
    return result
