from sqlalchemy.orm import Session
from app.dao.user_room_dao import UserRoomDAO
from app.model.user_room_model import UserRoom
from app.dao.lovelace_url_dao import LovelaceURLDAO


class UserRoomService:
    def __init__(self, db_session: Session):
        self.user_room_dao = UserRoomDAO(db_session)
        self.lovelace_url_dao = LovelaceURLDAO(db_session)

    def list_all(self):
        return self.user_room_dao.get_all()

    def get_by_id(self, record_id: int):
        record = self.user_room_dao.get_by_id(record_id)
        if not record:
            raise ValueError(f"UserRoom with id {record_id} not found.")
        return record

    def list_by_user_account(self, user_account: str):
        return self.user_room_dao.get_by_user_account(user_account)

    def list_by_room_id(self, room_id: str):
        return self.user_room_dao.get_by_room_id(room_id)

    def create(self, user_account: str, room_id: str):
        if not user_account or not room_id:
            raise ValueError("user_account and room_id are required.")

        existed = self.user_room_dao.get_unique(user_account, room_id)
        if existed:
            raise ValueError("Mapping already exists.")

        record = UserRoom(user_account=user_account, room_id=room_id)
        return self.user_room_dao.create(record)

    def update(self, record_id: int, user_account: str = None, room_id: str = None):
        record = self.get_by_id(record_id)

        if user_account is not None:
            record.user_account = user_account
        if room_id is not None:
            record.room_id = room_id

        # 如果用户传了双方都更新，需检查唯一键是否冲突
        if user_account is not None or room_id is not None:
            existed = self.user_room_dao.get_unique(record.user_account, record.room_id)
            if existed and existed.id != record.id:
                raise ValueError("Mapping already exists with given user_account and room_id.")

        return self.user_room_dao.update(record)

    def delete(self, record_id: int):
        record = self.get_by_id(record_id)
        self.user_room_dao.delete(record)
        return True

    def list_details_by_user_account(self, user_account: str):
        """返回包含用户账号、房间名、房间URL的映射详情列表。
        当前通过 UserRoom.room_id 与 LovelaceURL.id 进行关联（假设 room_id 存储的是 LovelaceURL.id）。
        如果实际是其他关联方式，请告知我调整。
        """
        mappings = self.user_room_dao.get_by_user_account(user_account)
        if not mappings:
            return []

        # 预取所有涉及的 room_id 对应的 LovelaceURL
        room_ids = [m.room_id for m in mappings]
        # 将 room_id 当作 LovelaceURL 的主键 id 来查找（如果是字符串，需要尝试转换）
        id_ints = []
        for rid in room_ids:
            try:
                id_ints.append(int(rid))
            except (TypeError, ValueError):
                continue

        # 构建 id -> LovelaceURL 映射
        lovelace_map = {}
        if id_ints:
            # 简单拉全量再过滤（DAO 暂无批量 by_ids 方法）
            all_records = self.lovelace_url_dao.get_all()
            for rec in all_records:
                if rec.id in id_ints:
                    lovelace_map[rec.id] = rec

        results = []
        for m in mappings:
            room_name = None
            room_url = None
            try:
                key = int(m.room_id)
                match = lovelace_map.get(key)
                if match:
                    room_name = match.room_name
                    room_url = match.url
            except (TypeError, ValueError):
                pass

            results.append({
                'id': m.id,
                'user_account': m.user_account,
                'room_name': room_name,
                'room_url': room_url,
                'room_id' : m.room_id,
            })

        return results


