import xbmc
import json
import urllib.request
import urllib.parse
from datetime import datetime

# 配置（仅保留必需项）
TMDB_CREDITS_URL = "https://api.themoviedb.org/3/tv/{tmdb_id}/credits?api_key={api_key}"
TMDB_TV_DETAILS_URL = "https://api.themoviedb.org/3/tv/{tmdb_id}?api_key={api_key}&append_to_response=credits"
TMDB_SEARCH_URL = "https://api.themoviedb.org/3/search/tv?api_key={api_key}&query={query}&language=en-US&page=1"
SKIN_STRING_DIRECTOR = "eptvshowid"  # 存储导演ID的皮肤字符串
SKIN_STRING_TMDB_ID = "eptvshowidactor"  # 存储剧集TMDB ID的皮肤字符串
API_KEY_SKIN_STRING = "tmdbapikey"  # 存储API Key的皮肤字符串名称

def get_tmdb_id_by_title_and_year(api_key, title, target_year_str):
    """通过剧集名+目标年份查询TMDB ID"""
    if not title:
        return ""
    
    target_year = int(target_year_str) if (target_year_str and target_year_str.isdigit()) else None
    encoded_title = urllib.parse.quote(title.strip())
    url = TMDB_SEARCH_URL.format(api_key=api_key, query=encoded_title)
    
    try:
        headers = {"User-Agent": "Mozilla/5.0"}
        req = urllib.request.Request(url, headers=headers)
        
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            results = data.get("results", [])
            
            if not results:
                return ""
            
            if len(results) == 1:
                return str(results[0].get("id", ""))
            
            # 多结果按年份筛选
            valid_results = []
            for result in results:
                first_air_date = result.get("first_air_date", "")
                if not first_air_date:
                    continue
                
                try:
                    show_year = datetime.strptime(first_air_date, "%Y-%m-%d").year
                except ValueError:
                    continue
                
                year_diff = abs(show_year - target_year) if target_year else float("inf")
                valid_results.append({
                    "tmdb_id": str(result.get("id", "")),
                    "show_year": show_year,
                    "first_air_date": first_air_date,
                    "year_diff": year_diff
                })
            
            if not valid_results:
                return ""
            
            valid_results.sort(key=lambda x: (x["year_diff"], x["first_air_date"]))
            return valid_results[0]["tmdb_id"]
    
    except Exception as e:
        xbmc.log(f"[简化版导演ID脚本] 查询TMDB ID失败：{str(e)}（标题='{title}'，年份='{target_year_str}'）", xbmc.LOGERROR)
        return ""

def get_director_id_from_credits(api_key, tmdb_id):
    """从credits接口获取导演ID（原逻辑）"""
    try:
        url = TMDB_CREDITS_URL.format(tmdb_id=tmdb_id, api_key=api_key)
        headers = {"User-Agent": "Mozilla/5.0"}
        req = urllib.request.Request(url, headers=headers)
        
        with urllib.request.urlopen(req, timeout=8) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            for crew in data.get("crew", []):
                if crew.get("job") == "Director":
                    return str(crew.get("id", ""))
        return ""
    
    except Exception as e:
        xbmc.log(f"[简化版导演ID脚本] credits接口请求失败：{str(e)}（TMDB ID：{tmdb_id}）", xbmc.LOGERROR)
        return ""

def get_director_id_from_details(api_key, tmdb_id):
    """从剧集主信息接口提取导演ID（备用逻辑）"""
    try:
        url = TMDB_TV_DETAILS_URL.format(tmdb_id=tmdb_id, api_key=api_key)
        headers = {"User-Agent": "Mozilla/5.0"}
        req = urllib.request.Request(url, headers=headers)
        
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            
            # 优先级1：created_by
            created_by = data.get("created_by", [])
            if created_by:
                return str(created_by[0].get("id", ""))
            
            # 优先级2：credits.directing
            credits = data.get("credits", {})
            directing = credits.get("directing", [])
            if directing:
                return str(directing[0].get("id", ""))
            
            # 优先级3：director_str（通过名称搜索）
            director_str = data.get("director_str", "").strip()
            if director_str and director_str != "N/A":
                first_director_name = director_str.split(",")[0].strip()
                if first_director_name:
                    return search_person_id_by_name(api_key, first_director_name)
            
            return ""
    
    except Exception as e:
        xbmc.log(f"[简化版导演ID脚本] 剧集主信息接口请求失败：{str(e)}（TMDB ID：{tmdb_id}）", xbmc.LOGERROR)
        return ""

def search_person_id_by_name(api_key, person_name):
    """通过人名搜索TMDB人物ID"""
    TMDB_PERSON_SEARCH_URL = "https://api.themoviedb.org/3/search/person?api_key={api_key}&query={query}&language=en-US&page=1"
    
    try:
        encoded_name = urllib.parse.quote(person_name.strip())
        url = TMDB_PERSON_SEARCH_URL.format(api_key=api_key, query=encoded_name)
        
        headers = {"User-Agent": "Mozilla/5.0"}
        req = urllib.request.Request(url, headers=headers)
        
        with urllib.request.urlopen(req, timeout=8) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            results = data.get("results", [])
            if results:
                return str(results[0].get("id", ""))
            return ""
    
    except Exception as e:
        xbmc.log(f"[简化版导演ID脚本] 人物搜索接口失败：{str(e)}（名称：{person_name}）", xbmc.LOGERROR)
        return ""

def main():
    # 1. 读取API Key
    tmdb_api_key = xbmc.getInfoLabel(f"Skin.String({API_KEY_SKIN_STRING})").strip()

    # 如果从皮肤读取失败，则使用默认的 API Key
    if not tmdb_api_key:
        tmdb_api_key = "a07324c669cac4d96789197134ce272b"
        xbmc.log(f"[简化版导演ID脚本] 警告：未从皮肤获取到API Key，将使用默认Key。", xbmc.LOGWARNING)

    # 2. 获取/查询剧集TMDB ID
    tmdb_id = xbmc.getInfoLabel("Container(99950).ListItem.Property(TMDb_id)").strip()
    if not (tmdb_id and tmdb_id.isdigit()):
        tvshow_title = xbmc.getInfoLabel("ListItem.TVShowTitle").strip()
        premiered_date = xbmc.getInfoLabel("ListItem.Premiered").strip()
        target_year_str = premiered_date.split("-")[0] if premiered_date else ""
        tmdb_id = get_tmdb_id_by_title_and_year(tmdb_api_key, tvshow_title, target_year_str)
    
    # 3. 验证TMDB ID有效性
    if not (tmdb_id and tmdb_id.isdigit()):
        xbmc.log(f"[简化版导演ID脚本] 错误：未获取到有效剧集TMDB ID", xbmc.LOGERROR)
        return

    # 4. 设置剧集TMDB ID到皮肤字符串
    try:
        xbmc.executebuiltin(f'Skin.SetString({SKIN_STRING_TMDB_ID},"{tmdb_id}")')
    except Exception as e:
        xbmc.log(f"[简化版导演ID脚本] 错误：设置{SKIN_STRING_TMDB_ID}失败：{str(e)}", xbmc.LOGERROR)

    # 5. 查询导演ID（原逻辑→备用逻辑）
    director_id = get_director_id_from_credits(tmdb_api_key, tmdb_id)
    if not director_id:
        xbmc.log(f"[简化版导演ID脚本] 警告：从credits接口未找到导演，尝试备用方案", xbmc.LOGWARNING)
        director_id = get_director_id_from_details(tmdb_api_key, tmdb_id)

    # 6. 设置导演ID到皮肤字符串
    if director_id:
        try:
            xbmc.executebuiltin(f'Skin.SetString({SKIN_STRING_DIRECTOR},"{director_id}")')
        except Exception as e:
            xbmc.log(f"[简化版导演ID脚本] 错误：设置{SKIN_STRING_DIRECTOR}失败：{str(e)}", xbmc.LOGERROR)
    else:
        xbmc.log(f"[简化版导演ID脚本] 错误：未获取到有效导演ID（剧集TMDB ID：{tmdb_id}）", xbmc.LOGERROR)

if __name__ == "__main__":
    main()