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

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from io import BytesIO
from PIL import Image
import base64

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():
    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。")


#2025.1.2新增template api

@app.route('/eli/new_assets/backgrounds/index', methods=['GET'])
def get_jytemplate_index():
    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 jsonify(data), 200
        except json.JSONDecodeError:
            return jsonify({"message": "Error decoding JSON from file."}), 500
    else:
        return jsonify({"message": "JSON file not found"}), 404

@app.route('/eli/new_assets/backgrounds/json_img',methods=['POST'])
def get_jytemplate_source_json_img():
    if request.content_type != "application/json":
        return jsonify({"error": "Unsupported Content-Type"}), 400
    try:
        json_data = request.get_json()
    except Exception as e:
        return jsonify({"error": "Unsupported Content-Type"}), 400
    if not json_data or "id" not in json_data:
        return jsonify({"error": "Unsupported Content-Type"}), 400

    asset_id = json_data["id"]
    if not asset_id:
        return jsonify({"message": "Missing 'id' parameter"}), 400

    asset_base_path = "/www/jy/sources"
    folder_path = os.path.join(asset_base_path, asset_id)
    json_file_path = os.path.join(folder_path, 'StudioData.json')
    img_file_path = os.path.join(folder_path, asset_id + '.png')

    if not os.path.exists(json_file_path):
        return jsonify({"message": "JSON file not found"}), 404
    if not os.path.exists(img_file_path):
        return jsonify({"message": "Image file not found"}), 404

    try:
        with open(json_file_path, 'r') as json_file:
            json_data = json_file.read()
        with open(img_file_path, 'rb') as img_file:
            img_data = img_file.read()

        boundary = "boundary12345"
        response = Response(
            f"--{boundary}\r\n"
            f"Content-Type: application/json\r\n\r\n"
            f"{json_data}\r\n"
            f"--{boundary}\r\n"
            f"Content-Type: image/png\r\n"
            f"Content-Disposition: attachment; filename={asset_id}.png\r\n\r\n"
        )
        response.data += img_data
        response.data += f"\r\n--{boundary}--\r\n".encode("utf-8")
        response.headers["Content-Type"] = f"multipart/mixed; boundary={boundary}"
        return response
    except Exception as e:
        return jsonify({"message": str(e)}), 500


@app.route('/eli/new_assets/backgrounds/img',methods=['POST'])
def get_jytemplate_source_img():
    if request.content_type != "application/json":
        return jsonify({"error": "Unsupported Content-Type"}), 400
    try:
        json_data = request.get_json()
    except Exception as e:
        return jsonify({"error": "Invalid JSON format"}), 400
    if not json_data or "id" not in json_data:
        return jsonify({"error": "Missing 'id' parameter"}), 400

    asset_id = json_data["id"]
    format = json_data["format"]
    if not asset_id:
        return jsonify({"message": "Missing 'id' parameter"}),400
    
    asset_base_path = "/www/jy/sources"
    folder_path = os.path.join(asset_base_path, asset_id)
    img_file_path = os.path.join(folder_path, asset_id + "." + format)
    if not os.path.exists(img_file_path):
        return jsonify({"message": "Image file not found"}),404

    try:
        return send_file(
            img_file_path,
            mimetype='image/png',
            as_attachment=False
        )
    except Exception as e:
        return jsonify({"message": str(e)}), 500

@app.route('/eli/new_assets/backgrounds/json',methods=['POST'])
def get_jytemplate_source_json():
    if request.content_type != "application/json":
        return jsonify({"error": "Unsupported Content-Type"}), 400
    try:
        json_data = request.get_json()
    except Exception as e:
        return jsonify({"error": "Invalid JSON format"}), 400
    if not json_data or "id" not in json_data:
        return jsonify({"error": "Missing 'id' parameter"}), 400
    asset_id = json_data["id"]
    if not asset_id:
        return jsonify({"error": "Missing 'id' parameter"}), 400
    asset_base_path = "/www/jy/sources"
    folder_path = os.path.join(asset_base_path, asset_id)
    json_file_path = os.path.join(folder_path, "StudioData.json")
    if not os.path.exists(json_file_path):
        return jsonify({"message": "json file not found"}),404
    
    try:
        with open(json_file_path, 'r') as json_file:
            json_data = json_file.read()
            return json_data
    except Exception as e:
        return jsonify({"message": str(e)}), 500


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


