import io
import os
import json
import base64
import requests
from pathlib import Path
import uuid
from urllib.parse import urlparse

import jingrow
from jingrow.ai.utils.utils import update_status_progress, update_progress, send_notification, get_jingrow_api_headers, get_jingrow_api_url, upload_image

# 调用新版Jingrow矢量图批量API
def call_jvector_api(image_urls):
    # 获取API URL
    api_url = f"{get_jingrow_api_url()}/jvector/batch"
    
    headers = get_jingrow_api_headers()
    if not headers:
        error_message = "Jingrow API 未设置，请在 AI设置 中设置 Jingrow Api Key 和 Jingrow Api Secret"
        send_notification(error_message)
        return None
    
    request_data = {"urls": image_urls}
    
    # 发送请求并获取流式响应
    response = requests.post(
        api_url,
        json=request_data,
        headers=headers,
        stream=True
    )
    
    if response.status_code != 200:
        try:
            error_data = response.json()
            error_message = error_data.get("message") or error_data.get("error") or f"API请求失败 (HTTP {response.status_code})"
        except:
            error_message = f"API请求失败 (HTTP {response.status_code})"
        
        if response.status_code in [401, 403]:
            auth_error_message = "API认证失败，请检查 Jingrow Api Key 和 Jingrow Api Secret 是否正确"
            send_notification(auth_error_message)
            return None
        
        send_notification(f"API请求失败: {error_message}")
        return None
    
    return response

# 处理矢量图转换任务的主函数
def process_jvector_task(pg_name, pagetype):
    try:
        pg = jingrow.get_pg(pagetype, pg_name)
     
        # 更新状态为"任务进行中"
        update_status_progress(pagetype, pg_name, "任务进行中", 20)
       
        file_pgs = jingrow.db.get_all(
            "File",
            {"attached_to_pagetype": pagetype, "attached_to_name": pg_name},
            ["file_url", "file_name"]
        )
            
        # 构建图片URL列表
        site_url = jingrow.utils.get_url()
        image_urls = []
        
        # 按照原始附件列表的顺序添加图片
        for img_file in file_pgs:
            # 检查文件扩展名
            if Path(img_file.file_name).suffix.lower() not in ['.png', '.jpg', '.jpeg']:
                continue
                
            # 构建完整URL
            full_image_url = f"{site_url}{img_file.file_url}"
            image_urls.append(full_image_url)
            
        # 反转列表顺序，使第一张图片排在前面
        image_urls.reverse()
        
        if not image_urls:
            update_status_progress(pagetype, pg_name, "任务未完成", 0)
            jingrow.log_error(f"未找到图片附件", f"{pagetype}:{pg_name}")
            return False
        
        update_progress(pg_name, 40, pagetype)
        
        # 调用批量API处理
        response = call_jvector_api(image_urls)
        if not response:
            update_status_progress(pagetype, pg_name, "任务未完成", 0)
            jingrow.log_error(f"API调用失败", f"{pagetype}:{pg_name}")
            return False
        
        # 处理流式响应
        processed_count = 0
        total_images = len(image_urls)
        
        for line in response.iter_lines():
            if line:
                try:
                    result = json.loads(line)
                    
                    if result.get('status') == 'success':
                        # 从URL中提取文件名
                        url_path = urlparse(result.get('original_url', '')).path
                        base_filename = os.path.splitext(os.path.basename(url_path))[0]
                        short_uuid = str(uuid.uuid4())[:8]  # 生成8位uuid
                        new_filename = f"{base_filename}_{short_uuid}.svg"
                        
                        # 解码SVG内容
                        if 'svg_content' in result:
                            svg_content = base64.b64decode(result['svg_content'])
                            
                            # 保存为文件对象
                            try:                
                                file_pg = jingrow.get_pg({
                                    "pagetype": "File",
                                    "attached_to_pagetype": pagetype,
                                    "attached_to_name": pg_name,
                                    "file_name": new_filename,
                                    "is_private": 0,
                                    "content": svg_content
                                })
                                file_pg.save()
                                jingrow.db.commit()
                                
                                processed_count += 1
                                # 更新进度
                                current_progress = 40 + int((processed_count / total_images) * 60)
                                update_progress(pg_name, current_progress, pagetype)
                                
                            except Exception as e:
                                jingrow.log_error(f"保存矢量图文件失败", f"{pagetype}:{pg_name}, 文件:{new_filename}, 错误: {str(e)}")
                                continue
                    else:
                        jingrow.log_error(f"处理图片失败", f"{pagetype}:{pg_name}, 错误: {result.get('message', '未知错误')}")
                        
                except json.JSONDecodeError as e:
                    jingrow.log_error(f"解析响应数据失败", f"{pagetype}:{pg_name}, 错误: {str(e)}")
                except Exception as e:
                    jingrow.log_error(f"处理响应时出错", f"{pagetype}:{pg_name}, 错误: {str(e)}")
        
        # 更新状态为"已转换为矢量图"
        update_status_progress(pagetype, pg_name, "已转换为矢量图", 100)
        
        return True
        
    except Exception as e:
        jingrow.log_error("处理矢量图转换任务时发生异常", f"{pagetype}:{pg_name}, 错误: {str(e)}")
        update_status_progress(pagetype, pg_name, "任务未完成", 0)
        return False
