package com.aiosman.ravenow.data

import com.aiosman.ravenow.data.api.ApiClient
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.annotations.SerializedName

/**
 * 推荐接口响应
 */
data class RecommendationsResponse(
    @SerializedName("success")
    val success: Boolean,
    @SerializedName("data")
    val data: List<RecommendationItem>
)

/**
 * 推荐项
 */
data class RecommendationItem(
    @SerializedName("type")
    val type: String,
    @SerializedName("id")
    val id: Long,
    @SerializedName("data")
    val data: Any // 根据type字段动态解析为不同类型
) {
    /**
     * 将data字段转换为PromptRecommendationData
     */
    fun toPromptData(): PromptRecommendationData? {
        if (type != "prompt") return null
        return try {
            val gson = Gson()
            val jsonString = gson.toJson(data)
            gson.fromJson(jsonString, PromptRecommendationData::class.java)
        } catch (e: JsonSyntaxException) {
            null
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 将data字段转换为PostRecommendationData (Moment)
     */
    fun toPostData(): PostRecommendationData? {
        if (type !in listOf("post_normal", "post_video", "post_news", "post_music")) return null
        return try {
            val gson = Gson()
            val jsonString = gson.toJson(data)
            gson.fromJson(jsonString, PostRecommendationData::class.java)
        } catch (e: JsonSyntaxException) {
            null
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 将data字段转换为RoomRecommendationData
     */
    fun toRoomData(): RoomRecommendationData? {
        if (type != "room") return null
        return try {
            val gson = Gson()
            val jsonString = gson.toJson(data)
            gson.fromJson(jsonString, RoomRecommendationData::class.java)
        } catch (e: JsonSyntaxException) {
            null
        } catch (e: Exception) {
            null
        }
    }
}

/**
 * Prompt类型推荐数据
 */
data class PromptRecommendationData(
    @SerializedName("id")
    val id: Long,
    @SerializedName("title")
    val title: String,
    @SerializedName("desc")
    val desc: String,
    @SerializedName("createdAt")
    val createdAt: String,
    @SerializedName("updatedAt")
    val updatedAt: String,
    @SerializedName("avatar")
    val avatar: String? = null,
    @SerializedName("avatarDirectUrl")
    val avatarDirectUrl: String? = null,
    @SerializedName("author")
    val author: String? = null,
    @SerializedName("isPublic")
    val isPublic: Boolean = false,
    @SerializedName("openId")
    val openId: String,
    @SerializedName("breakMode")
    val breakMode: Boolean = false,
    @SerializedName("useCount")
    val useCount: Int? = null,
    @SerializedName("translations")
    val translations: Map<String, Map<String, String>>? = null,
    @SerializedName("translation")
    val translation: Map<String, String>? = null,
    @SerializedName("details")
    val details: PromptDetails? = null,
    @SerializedName("aiUserProfile")
    val aiUserProfile: AIUserProfile? = null,
    @SerializedName("creatorProfile")
    val creatorProfile: CreatorProfile? = null
)

/**
 * Prompt详细信息
 */
data class PromptDetails(
    @SerializedName("gender")
    val gender: String? = null,
    @SerializedName("age")
    val age: Int? = null,
    @SerializedName("mbti")
    val mbti: String? = null,
    @SerializedName("constellation")
    val constellation: String? = null,
    @SerializedName("nickname")
    val nickname: String? = null,
    @SerializedName("birthday")
    val birthday: String? = null,
    @SerializedName("signature")
    val signature: String? = null,
    @SerializedName("nationality")
    val nationality: String? = null,
    @SerializedName("mainLanguage")
    val mainLanguage: String? = null,
    @SerializedName("worldview")
    val worldview: String? = null,
    @SerializedName("habits")
    val habits: String? = null,
    @SerializedName("hobbies")
    val hobbies: String? = null,
    @SerializedName("occupation")
    val occupation: String? = null,
    @SerializedName("expertise")
    val expertise: String? = null,
    @SerializedName("socialActivityLvl")
    val socialActivityLvl: String? = null
)

/**
 * AI用户资料
 */
data class AIUserProfile(
    @SerializedName("id")
    val id: Long,
    @SerializedName("username")
    val username: String? = null,
    @SerializedName("nickname")
    val nickname: String,
    @SerializedName("avatar")
    val avatar: String? = null,
    @SerializedName("avatarMedium")
    val avatarMedium: String? = null,
    @SerializedName("avatarLarge")
    val avatarLarge: String? = null,
    @SerializedName("avatarDirectUrl")
    val avatarDirectUrl: String? = null,
    @SerializedName("avatarMediumDirectUrl")
    val avatarMediumDirectUrl: String? = null,
    @SerializedName("avatarLargeDirectUrl")
    val avatarLargeDirectUrl: String? = null,
    @SerializedName("bio")
    val bio: String? = null,
    @SerializedName("trtcUserId")
    val trtcUserId: String? = null,
    @SerializedName("chatAIId")
    val chatAIId: String? = null,
    @SerializedName("aiAccount")
    val aiAccount: Boolean = true,
    @SerializedName("aiRoleAvatar")
    val aiRoleAvatar: String? = null,
    @SerializedName("aiRoleAvatarMedium")
    val aiRoleAvatarMedium: String? = null,
    @SerializedName("aiRoleAvatarLarge")
    val aiRoleAvatarLarge: String? = null,
    @SerializedName("aiRoleAvatarDirectUrl")
    val aiRoleAvatarDirectUrl: String? = null,
    @SerializedName("aiRoleAvatarMediumDirectUrl")
    val aiRoleAvatarMediumDirectUrl: String? = null,
    @SerializedName("aiRoleAvatarLargeDirectUrl")
    val aiRoleAvatarLargeDirectUrl: String? = null
)

/**
 * 创建者资料
 */
data class CreatorProfile(
    @SerializedName("id")
    val id: Long,
    @SerializedName("username")
    val username: String? = null,
    @SerializedName("nickname")
    val nickname: String,
    @SerializedName("avatar")
    val avatar: String? = null,
    @SerializedName("avatarMedium")
    val avatarMedium: String? = null,
    @SerializedName("avatarLarge")
    val avatarLarge: String? = null,
    @SerializedName("avatarDirectUrl")
    val avatarDirectUrl: String? = null,
    @SerializedName("avatarMediumDirectUrl")
    val avatarMediumDirectUrl: String? = null,
    @SerializedName("avatarLargeDirectUrl")
    val avatarLargeDirectUrl: String? = null,
    @SerializedName("bio")
    val bio: String? = null,
    @SerializedName("trtcUserId")
    val trtcUserId: String? = null,
    @SerializedName("chatAIId")
    val chatAIId: String? = null,
    @SerializedName("aiAccount")
    val aiAccount: Boolean = false,
    @SerializedName("aiRoleAvatar")
    val aiRoleAvatar: String? = null,
    @SerializedName("aiRoleAvatarMedium")
    val aiRoleAvatarMedium: String? = null,
    @SerializedName("aiRoleAvatarLarge")
    val aiRoleAvatarLarge: String? = null,
    @SerializedName("aiRoleAvatarDirectUrl")
    val aiRoleAvatarDirectUrl: String? = null,
    @SerializedName("aiRoleAvatarMediumDirectUrl")
    val aiRoleAvatarMediumDirectUrl: String? = null,
    @SerializedName("aiRoleAvatarLargeDirectUrl")
    val aiRoleAvatarLargeDirectUrl: String? = null
)

/**
 * Post类型推荐数据（复用Moment中的结构）
 * 支持 post_normal, post_video, post_news, post_music
 */
typealias PostRecommendationData = Moment

/**
 * Room类型推荐数据
 */
data class RoomRecommendationData(
    @SerializedName("id")
    val id: Long,
    @SerializedName("name")
    val name: String,
    @SerializedName("description")
    val description: String,
    @SerializedName("createdAt")
    val createdAt: String? = null,
    @SerializedName("updatedAt")
    val updatedAt: String? = null,
    @SerializedName("cover")
    val cover: String? = null,
    @SerializedName("coverDirectUrl")
    val coverDirectUrl: String? = null,
    @SerializedName("avatar")
    val avatar: String? = null,
    @SerializedName("avatarDirectUrl")
    val avatarDirectUrl: String? = null,
    @SerializedName("recommendBanner")
    val recommendBanner: String? = null,
    @SerializedName("trtcRoomId")
    val trtcRoomId: String? = null,
    @SerializedName("trtcType")
    val trtcType: String? = null,
    @SerializedName("isRecommended")
    val isRecommended: Boolean = false,
    @SerializedName("allowInHot")
    val allowInHot: Boolean = false,
    @SerializedName("language")
    val language: String? = null,
    @SerializedName("maxTotal")
    val maxTotal: Int? = null,
    @SerializedName("privateFeePaid")
    val privateFeePaid: Boolean = false
)

/**
 * 推荐Service接口
 */
interface RecommendationService {
    /**
     * 获取推荐列表
     * @param pool 推荐池名称（可选）
     * @param count 返回数量（可选，默认10，最大50）
     * @param lang 语言代码（可选）
     * @param promptReplaceTrans 是否用翻译覆盖原字段（可选，仅对prompt类型生效）
     * @return 推荐项列表
     */
    suspend fun getRecommendations(
        pool: String? = null,
        count: Int? = null,
        lang: String? = null,
        promptReplaceTrans: Boolean? = null
    ): List<RecommendationItem>
}

/**
 * 推荐Service实现
 */
class RecommendationServiceImpl : RecommendationService {
    override suspend fun getRecommendations(
        pool: String?,
        count: Int?,
        lang: String?,
        promptReplaceTrans: Boolean?
    ): List<RecommendationItem> {
        val resp = ApiClient.api.getRecommendations(
            pool = pool,
            count = count,
            lang = lang,
            promptReplaceTrans = promptReplaceTrans
        )
        if (resp.isSuccessful) {
            val body = resp.body()
            if (body != null && body.success) {
                return body.data
            }
        }
        throw ServiceException("Failed to get recommendations")
    }
}

/**
 * CreatorProfile 扩展函数，转换为 CreatorProfileEntity
 */
fun CreatorProfile.toCreatorProfileEntity(): com.aiosman.ravenow.entity.CreatorProfileEntity {
    return com.aiosman.ravenow.entity.CreatorProfileEntity(
        id = id,
        username = username,
        nickname = nickname,
        avatar = avatar?.let {
            if (it.isNotEmpty()) "${ApiClient.BASE_SERVER}$it" else null
        },
        bio = bio,
        trtcUserId = trtcUserId,
        chatAIId = chatAIId,
        aiAccount = aiAccount
    )
}

