"""Runtime identity resolution helpers."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

OWNER_SESSION_ID = "main"
OWNER_USER_ID = "owner"


@dataclass(frozen=True, slots=True)
class ActorIdentity:
    """Resolved actor identity for one inbound turn."""

    identity_status: str
    canonical_user_id: str | None = None
    role: str = "unknown"
    is_owner: bool = False
    channel: str | None = None
    external_id: str | None = None


def build_local_owner_identity() -> ActorIdentity:
    """Return the fixed owner identity used by local CLI turns."""
    return ActorIdentity(
        identity_status="owner",
        canonical_user_id=OWNER_USER_ID,
        role="owner",
        is_owner=True,
        channel="cli",
        external_id=OWNER_USER_ID,
    )


def build_unknown_identity(*, channel: str | None, external_id: str | None) -> ActorIdentity:
    """Return an unverified actor identity."""
    return ActorIdentity(
        identity_status="unknown",
        canonical_user_id=None,
        role="unknown",
        is_owner=False,
        channel=channel,
        external_id=external_id,
    )


def build_bound_identity(
    *,
    channel: str,
    external_id: str,
    canonical_user_id: str,
    role: str,
) -> ActorIdentity:
    """Return one bound actor identity."""
    normalized_role = role.strip().lower() or "user"
    return ActorIdentity(
        identity_status="owner" if normalized_role == "owner" else "known_user",
        canonical_user_id=canonical_user_id.strip() or None,
        role=normalized_role,
        is_owner=normalized_role == "owner",
        channel=channel,
        external_id=external_id,
    )


def is_direct_channel_message(message: Any) -> bool:
    """Best-effort detection for direct messages across supported channels."""
    metadata = getattr(message, "metadata", {}) or {}
    chat_type = str(metadata.get("chat_type") or "").strip().lower()
    if chat_type:
        return chat_type not in {"group", "channel"}
    if "is_group" in metadata:
        return not bool(metadata.get("is_group"))
    reply_target_type = str(getattr(message, "reply_target_type", "") or "").strip().lower()
    return reply_target_type not in {"group", "chat_id"}


def resolve_session_id_for_channel(
    *,
    actor: ActorIdentity,
    channel: str,
    chat_id: str,
    is_direct: bool,
) -> str:
    """Resolve the runtime session id for one channel message."""
    if is_direct and actor.is_owner:
        return OWNER_SESSION_ID
    if is_direct and actor.canonical_user_id:
        return f"user:{actor.canonical_user_id}"
    return f"{channel}:{chat_id}"
