import logging
import httpx
from sqlalchemy import select

from .. import settings
from ..db import AsyncSessionLocal

log = logging.getLogger(__name__)


class SlackActor:
    def __init__(self, slack_user_id: str, user_id: str, account_id: str, role: str):
        self.slack_user_id = slack_user_id
        self.user_id = user_id
        self.account_id = account_id
        self.role = role


async def map_slack_user(slack_user_id: str) -> SlackActor | None:
    try:
        # Dev shortcut
        if (settings.ENV or "").lower().startswith("dev"):
            return SlackActor(
                slack_user_id, "dev-user", settings.DEV_ACCOUNT_ID, "admin"
            )

        token = settings.SLACK_BOT_TOKEN
        if not token:
            return None
        async with httpx.AsyncClient(timeout=10) as client:
            r = await client.get(
                "https://slack.com/api/users.info",
                params={"user": slack_user_id},
                headers={"Authorization": f"Bearer {token}"},
            )
            data = r.json()
        if not data.get("ok"):
            return None
        email = (
            (((data.get("user") or {}).get("profile") or {}).get("email") or "")
            .lower()
            .strip()
        )
        if not email:
            return None
        from ...models import User

        async with AsyncSessionLocal() as db:
            row = (
                await db.execute(select(User).where(User.email == email))
            ).scalar_one_or_none()
            if not row:
                return None
            role = getattr(row, "role", "viewer")
            role = getattr(role, "value", role)
            return SlackActor(
                slack_user_id, str(row.id), str(row.account_id or ""), str(role)
            )
    except Exception:
        log.exception("map_slack_user failed")
        return None
