"""
CNP Solutions field-support operator login (break-glass ERP access).

Authenticates with configured credentials (default cnpadmin) and enters any
company/branch context typed on the login page — full super_admin within that tenant.
Separate from God Mode (/platform-admin) which manages all tenants at platform level.
"""
from __future__ import annotations

import secrets
from typing import Any, Dict, Optional

from sqlalchemy.orm import Session

from app.core.config import settings
from app.core.security import get_password_hash
from app.models.user import User

CNP_SUPPORT_USER_ID = "cnp-support-00000001"
CNP_SUPPORT_DB_USERNAME = "__cnp_support_system__"


def is_cnp_support_enabled() -> bool:
    if not settings.cnp_support_enabled:
        return False
    return bool((settings.cnp_support_password or "").strip())


def verify_cnp_support_credentials(username: str, password: str) -> bool:
    if not is_cnp_support_enabled():
        return False
    expected_user = (settings.cnp_support_username or "cnpadmin").strip().lower()
    expected_pass = (settings.cnp_support_password or "").strip()
    if not expected_pass:
        return False
    return (
        (username or "").strip().lower() == expected_user
        and secrets.compare_digest((password or "").strip(), expected_pass)
    )


def ensure_cnp_support_user(db: Session) -> User:
    """System user row for FK integrity (created_by, audit logs). Not used for normal login."""
    user = db.query(User).filter(User.id == CNP_SUPPORT_USER_ID).first()
    if user:
        return user
    user = User(
        id=CNP_SUPPORT_USER_ID,
        username=CNP_SUPPORT_DB_USERNAME,
        password_digest=get_password_hash(secrets.token_urlsafe(32)),
        role="super_admin",
        email="support@cnpsolutions.co.bw",
        first_name="CNP",
        last_name="Support",
        active=True,
        company_id=None,
        branch_id=None,
        notes="System account for CNP field-support ERP login — do not delete",
    )
    db.add(user)
    db.flush()
    return user


class CnpSupportUser:
    """In-memory user overlay for support sessions — full super_admin in chosen tenant."""

    cnp_support = True

    def __init__(
        self,
        *,
        company_id: Optional[str],
        branch_id: Optional[str],
        username: Optional[str] = None,
    ):
        self.id = CNP_SUPPORT_USER_ID
        self.username = username or settings.cnp_support_username or "cnpadmin"
        self.role = "super_admin"
        self.company_id = company_id
        self.branch_id = branch_id
        self.active = True
        self.is_active = True
        self.email = "support@cnpsolutions.co.bw"
        self.first_name = "CNP"
        self.last_name = "Support"


def support_user_from_payload(payload: Dict[str, Any], db: Session) -> CnpSupportUser:
    if payload.get("cnp_support") is not True:
        raise ValueError("Not a CNP support token")
    ensure_cnp_support_user(db)
    return CnpSupportUser(
        company_id=payload.get("company_id"),
        branch_id=payload.get("branch_id"),
        username=payload.get("username"),
    )


def is_cnp_support_user(user: Any) -> bool:
    return getattr(user, "cnp_support", False) is True or getattr(user, "id", None) == CNP_SUPPORT_USER_ID
