"""Public (authenticated-user) endpoints for subscription info & xtream resolution."""
from fastapi import APIRouter, HTTPException, Request

from core.auth import get_current_user
from routes.admin_users import _get_settings_doc
from routes.auth import _shape_user, get_db

router = APIRouter(prefix="/api/subscription", tags=["subscription"])


def _build_source(source_type: str, url: str, user: str, pwd: str, mac: str) -> dict:
    """Build a normalized source dict from DB fields."""
    if not source_type or not url:
        return {}
    src: dict = {"type": source_type, "url": url}
    if source_type == "xtream":
        src["username"] = user
        src["password"] = pwd
    elif source_type == "stalker":
        src["mac"] = mac
    # m3u: url is the playlist URL, no extra creds needed
    return src


@router.get("/status")
async def status(request: Request):
    """Returns subscription + xtream info + hybrid dual-source for the logged-in user.

    Response shape:
      user: { ... }
      xtream: { server, username, password }        ← legacy single-source
      live_source: { type, url, username?, password?, mac? }  ← Source A
      vod_source:  { type, url, username?, password?, mac? }  ← Source B
      whatsapp_number: str
    """
    user = await get_current_user(request)
    db = get_db()
    shaped = _shape_user(await db.users.find_one({"id": user["id"]}, {"_id": 0}))
    settings = await _get_settings_doc(db)
    raw_user = await db.users.find_one({"id": user["id"]}, {"_id": 0}) or {}

    # ── Legacy single-source resolution (backwards compat) ──
    #
    # BUG-2 FIX (2026-05): make Own-mode strictly isolated. If a user is
    # configured as `xtream_mode == "own"` the system MUST NEVER fall
    # back to the global shared credentials — not even when the user's
    # own server/username/password fields are empty. Empty Own creds
    # mean "this account is misconfigured", and the client should
    # display an explicit error, not silently use the shared line.
    #
    # We additionally surface the resolved mode + a `xtream_configured`
    # flag in the response so the client can show the right UI.
    resolved_xtream = {"server": "", "username": "", "password": ""}
    resolved_mode = "shared"          # what we actually executed
    xtream_configured = False         # creds are present + non-empty
    if shaped.get("role") == "user":
        mode = shaped.get("xtream_mode", "shared")
        if mode == "own":
            # Strict isolation: ONLY the user's own credentials, never
            # fall back to shared. Even if all three fields are blank
            # we return blanks (NOT shared creds).
            own_server = shaped.get("xtream_server", "") or ""
            own_user = shaped.get("xtream_username", "") or ""
            own_pass = shaped.get("xtream_password", "") or ""
            resolved_xtream = {
                "server": own_server,
                "username": own_user,
                "password": own_pass,
            }
            resolved_mode = "own"
            xtream_configured = bool(own_server and own_user and own_pass)
        else:
            shared_server = settings.get("shared_xtream_server", "") or ""
            shared_user = settings.get("shared_xtream_username", "") or ""
            shared_pass = settings.get("shared_xtream_password", "") or ""
            resolved_xtream = {
                "server": shared_server,
                "username": shared_user,
                "password": shared_pass,
            }
            resolved_mode = "shared"
            xtream_configured = bool(shared_server and shared_user and shared_pass)

    # ── Hybrid dual-source ──
    live_source: dict = {}
    vod_source: dict = {}
    if shaped.get("role") == "user":
        live_source = _build_source(
            raw_user.get("live_source_type", ""),
            raw_user.get("live_url", ""),
            raw_user.get("live_user", ""),
            raw_user.get("live_pass", ""),
            raw_user.get("live_mac", ""),
        )
        vod_source = _build_source(
            raw_user.get("vod_source_type", ""),
            raw_user.get("vod_url", ""),
            raw_user.get("vod_user", ""),
            raw_user.get("vod_pass", ""),
            raw_user.get("vod_mac", ""),
        )

    # If expired, blank everything
    if shaped.get("is_expired"):
        resolved_xtream = {"server": "", "username": "", "password": ""}
        live_source = {}
        vod_source = {}
        xtream_configured = False

    return {
        "user": shaped,
        "xtream": resolved_xtream,
        # BUG-2 FIX: explicit mode + configured flag so the client can
        # render an "Own server, but credentials missing" error rather
        # than silently falling back to a shared profile.
        "xtream_mode": resolved_mode,
        "xtream_configured": xtream_configured,
        "live_source": live_source,
        "vod_source": vod_source,
        "whatsapp_number": settings.get("whatsapp_number", ""),
    }
