import os
import json
from flask import Flask, request, jsonify
from PIL import Image
from moviepy.editor import VideoFileClip

app = Flask(__name__)


def get_screen_orientation(file_path):
    if file_path.endswith(('.jpg', '.png')):
        image = Image.open(file_path)
        width, height = image.size
        if width > height:
            return "horizontal"
        else:
            return "vertical"
    else:
        clip = VideoFileClip(file_path)
        width, height = clip.size
        clip.close()
        if width > height:
            return "horizontal"
        else:
            return "vertical"

def get_icon_format(folder_path, folder):
    icon_file_prefix = f"icon_{folder}"
    for file in os.listdir(folder_path):
        if file.startswith(icon_file_prefix):
            return file.split('.')[-1]
    return None

def read_order_list(file_path):
    with open(file_path, 'r') as file:
        return [line.strip() for line in file]

def generate_assets_json(assets_type):
    directory = "/var/www/html/eli/new_assets/" + assets_type
    assets = []
    for folder in os.listdir(directory):
        folder_path = os.path.join(directory, folder)
        if os.path.isdir(folder_path):
            target_file_prefix = folder + '.'  # 文件夹同名文件的前缀
            icon_format = get_icon_format(folder_path, folder)
            for file in os.listdir(folder_path):
                if file.startswith(target_file_prefix):
                    format = file.split('.')[-1]
                    asset = {"id": folder, "format": format}
                    if format in ["jpg", "png", "mp4"]:
                        file_path = os.path.join(folder_path, file)
                        screen = get_screen_orientation(file_path)
                        asset["screen"] = screen
                    if icon_format:
                        asset["iconFormat"] = icon_format
                    assets.append(asset)
                    break

    if assets_type == 'vdstreamers':
        order_list = read_order_list('/var/www/html/eli/new_assets/vdstreamers/order_list.txt')
        assets.sort(key=lambda asset: order_list.index(asset["id"]) if asset["id"] in order_list else len(order_list))

    if assets_type == 'backgrounds':
        order_list = read_order_list('/var/www/html/eli/new_assets/backgrounds/order_list.txt')
        assets.sort(key=lambda asset: order_list.index(asset["id"]) if asset["id"] in order_list else len(order_list))
            
    return {f"{assets_type}": assets}

@app.route('/assets_download', methods=['GET'])
def get_assets():
    assets_type = request.args.get('assets_type')
    if not assets_type:
        return jsonify({"error": "assets_type parameter is required"}), 400
    assets_json = generate_assets_json(assets_type)
    return jsonify(assets_json)

import pymysql

@app.route('/get_account_model_assets', methods=['GET'])
def get_account_model_assets():
    # account = "EL2024101603"
    db_config = {
        "host": "8.129.147.237",
        "user": "root",
        "password": "AMAIGC080523@",
        "database": "elai",
        "charset": "utf8mb4"
    }
    account = request.args.get('account')
    conn = None
    cursor = None

    try:
        # 连接数据库
        conn = pymysql.connect(**db_config)
        cursor = conn.cursor()

        # 从 account_assets 表获取 asset_primkey
        cursor.execute("SELECT asset_primkey FROM account_assets WHERE account = %s", (account,))
        result = cursor.fetchone()

        if not result:
            return jsonify({"error": "Account not found"}), 404

        # 将 asset_primkey 转为列表
        asset_primkey_list = json.loads(result[0])  # 假设 asset_primkey 存储为 JSON 字符串

        # 根据 asset_primkey 查询 elai_assets 表
        cursor.execute(
            "SELECT id, format, icon_format FROM elai_assets WHERE primkey IN %s",
            (tuple(asset_primkey_list),)
        )
        assets = cursor.fetchall()

        # 整理为指定格式
        formatted_assets = [
            {"id": asset[0], "format": asset[1], "iconFormat": asset[2]} for asset in assets
        ]

        return jsonify({"vdstreamers": formatted_assets})

    except pymysql.MySQLError as e:
        return jsonify({"error": f"Database error: {e}"}), 500

    finally:
        # 确保关闭 cursor 和 conn
        if cursor is not None:
            cursor.close()
        if conn is not None:
            conn.close()

@app.route('/get_account_alivoice', methods=['GET'])
def check_account_ali_voice():
    db_connection = pymysql.connect(
        host="8.129.147.237",         
        user="root",
        password="AMAIGC080523@",
        database="elai",
        charset="utf8mb4"
    )

    cursor = db_connection.cursor(pymysql.cursors.DictCursor)
    account = request.args.get('account')
    cursor.execute("SELECT voice_primkey FROM account_ali_voice WHERE account = %s", (account,))

    result = cursor.fetchone()

    if result:
        try:
            voice_primkey = json.loads(result["voice_primkey"])
        except json.JSONDecodeError:
            print("voice_primkey 字段的值不是有效的 JSON 格式")
            cursor.close()
            db_connection.close()
            exit()

        cursor.execute("SELECT Name, Remark, LogicName, Sex, Language, SupportTimestamp FROM elai_ali_voice WHERE primkey IN (%s)" % ','.join(['%s'] * len(voice_primkey)),tuple(voice_primkey))

        voices = cursor.fetchall()

        json_result = {
            "PrefabSoundDatas": []
        }

        for voice in voices:
            json_result["PrefabSoundDatas"].append({
                "Name": voice["Name"],
                "Remark": voice["Remark"],
                "LogicName": voice["LogicName"],
                "Sex": voice["Sex"],
                "Language":voice["Language"],
                "SubtitlesSupport":voice["SupportTimestamp"]
            })

        return json.dumps(json_result, ensure_ascii=False, indent=4)
    else:
        print("没有找到对应的 account 或 voice_primkey。")

@app.route('/get_jytemplate_index', methods=['GET'])
    file_path = '/www/jy/jsonData/template_index.json'

    if os.path.exists(file_path):
        try:
            with open(file_path, 'r') as json_file:
            data = json.load(json_file)
            return JSONResponse(content=data,status_code=200)
        except json.JSONDecodeError:
            return JSONResponse(content={"message":"Error decoding JSON from file."},status_code=500)
    else:
        return JSONResponse(content={"message":"JSON file not found"},status_code=404)

@app.route('/get_jytemplate_source',methods=['POST'])
def get_jytemplate_source{}:
    
    data = request.get_json()
    if not data or 'id' not in data:
        raise HTTPException(status_code=400, detail="Missing 'id' parameter")
    asset_id = data['id']
    asset_base_path = /www/jy/sources

    folder_path = os.path.join(asset__path,asset_id)
    if not os.path.exists(folder_path) or not os.path.isdir(folder_path):
        raise HTTPException(status_code=404, detail=f"Folder for id '{asset_id}' not found")

    json_file_path = os.path.join(folder_path,'data.json')
    img_file_path = os.path.join(folder_path,'img.png')

    if not os.path.exists(json_file_path):
        raise HTTPException(status_code=404, detail=f"JSON file not found in folder for id '{asset_id}'")

    if not os.path.exists(img_file_path):
        raise HTTPException(status_code=404, detail=f"PNG image not found in folder for id '{asset_id}'")
    
    try:
        with open(json_file_path,'r') as json_file:
            json_data = json.load(json_file)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error reading JSON file: {str(e)}")
    
    response = JSONResponse(content="StudioData:",json_data,status_code=200)

    try:
        img_file = open(img_file_path,'rb')
        img_data = img_file.read()
        img_file.close()

        img_io = BytesIO(img_data)
        response.headers['X-Image'] = img.io.getValue()

        return response
    except Exception as e:
        raise HTTPException(status_code=200,detail=f"Error reading img file:{str(e)}")

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)


