#!/usr/bin/env python3
"""
Image Generation MCP Server
Use/UsingOpenAI DALL-E APIProvideAI图像生Success能
"""

import json
import requests
import os
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("AI Image Generation")

@mcp.tool()
def generate_image(prompt: str, model: str = "dall-e-3", size: str = "1024x1024", quality: str = "standard", n: int = 1):
    """生成AI图像"""
    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        return {"error": "Need to set OPENAI_API_KEY environment variable"}
    
    # 验证Parameter
    valid_models = ["dall-e-3", "dall-e-2"]
    if model not in valid_models:
        return {"error": f"Model必须是: {', '.join(valid_models)}"}
    
    valid_sizes = {
        "dall-e-3": ["1024x1024", "1792x1024", "1024x1792"],
        "dall-e-2": ["256x256", "512x512", "1024x1024"]
    }
    
    if size not in valid_sizes[model]:
        return {"error": f"{model} Support的尺寸: {', '.join(valid_sizes[model])}"}
    
    valid_qualities = ["standard", "hd"]
    if quality not in valid_qualities:
        return {"error": f"质量必须是: {', '.join(valid_qualities)}"}
    
    # DALL-E-3 Limit
    if model == "dall-e-3":
        if n > 1:
            return {"error": "DALL-E-3 每次只能生成1张图片"}
        if quality == "hd" and size == "1024x1024":
            pass  # Support的组合
        elif quality == "hd" and size in ["1792x1024", "1024x1792"]:
            pass  # Support的组合
        elif quality == "standard":
            pass  # 所有尺寸都Support标准质量
    
    # 构建Request
    url = "https://api.openai.com/v1/images/generations"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": model,
        "prompt": prompt,
        "n": n,
        "size": size
    }
    
    # DALL-E-3 特有Parameter
    if model == "dall-e-3":
        data["quality"] = quality
    
    try:
        response = requests.post(url, headers=headers, json=data, timeout=60)
        result = response.json()
        
        if response.status_code == 200:
            images = []
            for img_data in result.get("data", []):
                images.append({
                    "url": img_data.get("url"),
                    "revised_prompt": img_data.get("revised_prompt")  # DALL-E-3 Provide修订后的提示词
                })
            
            # 计算估算成本
            cost_info = calculate_cost(model, size, quality, n)
            
            return {
                "prompt": prompt,
                "model": model,
                "size": size,
                "quality": quality,
                "images": images,
                "cost_estimate": cost_info,
                "total_images": len(images)
            }
        else:
            error_msg = result.get("error", {}).get("message", "未知Error")
            return {"error": f"图像生成Failed: {error_msg}"}
    except Exception as e:
        return {"error": f"RequestFailed: {str(e)}"}

@mcp.tool()
def edit_image(image_url: str, mask_url: str, prompt: str, n: int = 1, size: str = "1024x1024"):
    """编辑图像（Need/Require原图和遮罩）"""
    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        return {"error": "Need to set OPENAI_API_KEY environment variable"}
    
    # 注意：这个功能Need/Require上传图像File，这里Provide接口Description
    return {
        "note": "图像编辑功能Need/Require上传图像File",
        "requirements": [
            "原始图像File（PNG格式，小于4MB）",
            "遮罩图像File（PNG格式，透明区域表示要编辑的部分）",
            "编辑提示词"
        ],
        "supported_sizes": ["256x256", "512x512", "1024x1024"],
        "api_endpoint": "https://api.openai.com/v1/images/edits",
        "method": "POST with multipart/form-data",
        "cost": "每张图片 $0.020 (1024×1024)"
    }

@mcp.tool()
def create_variation(image_url: str, n: int = 1, size: str = "1024x1024"):
    """创建图像变体"""
    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        return {"error": "Need to set OPENAI_API_KEY environment variable"}
    
    # 注意：这个功能Need/Require上传图像File
    return {
        "note": "图像变体功能Need/Require上传图像File",
        "requirements": [
            "原始图像File（PNG格式，正方形，小于4MB）"
        ],
        "supported_sizes": ["256x256", "512x512", "1024x1024"],
        "api_endpoint": "https://api.openai.com/v1/images/variations",
        "method": "POST with multipart/form-data",
        "cost": "每张图片 $0.020 (1024×1024)"
    }

def calculate_cost(model: str, size: str, quality: str = "standard", n: int = 1):
    """计算图像生成成本"""
    # DALL-E-3 定价
    if model == "dall-e-3":
        if quality == "standard":
            if size == "1024x1024":
                cost_per_image = 0.040
            elif size in ["1792x1024", "1024x1792"]:
                cost_per_image = 0.080
        elif quality == "hd":
            if size == "1024x1024":
                cost_per_image = 0.080
            elif size in ["1792x1024", "1024x1792"]:
                cost_per_image = 0.120
    
    # DALL-E-2 定价
    elif model == "dall-e-2":
        if size == "1024x1024":
            cost_per_image = 0.020
        elif size == "512x512":
            cost_per_image = 0.018
        elif size == "256x256":
            cost_per_image = 0.016
    
    total_cost = cost_per_image * n
    
    return {
        "cost_per_image": f"${cost_per_image:.3f}",
        "total_cost": f"${total_cost:.3f}",
        "currency": "USD"
    }

@mcp.tool()
def get_pricing_info():
    """Get/Fetch图像生成定价Info/Information"""
    return {
        "dall_e_3": {
            "standard_quality": {
                "1024x1024": "$0.040 per image",
                "1792x1024": "$0.080 per image", 
                "1024x1792": "$0.080 per image"
            },
            "hd_quality": {
                "1024x1024": "$0.080 per image",
                "1792x1024": "$0.120 per image",
                "1024x1792": "$0.120 per image"
            },
            "limitations": [
                "每次Request只能生成1张图片",
                "更高质量和创意性",
                "自动提示词优化"
            ]
        },
        "dall_e_2": {
            "pricing": {
                "1024x1024": "$0.020 per image",
                "512x512": "$0.018 per image",
                "256x256": "$0.016 per image"
            },
            "limitations": [
                "每次RequestAt most10张图片",
                "较低质量但更便宜",
                "无提示词优化"
            ]
        },
        "other_operations": {
            "image_edit": "$0.020 per image (1024x1024)",
            "image_variation": "$0.020 per image (1024x1024)"
        },
        "currency": "USD",
        "last_updated": "2024-01"
    }

@mcp.tool()
def get_model_comparison():
    """Get/FetchModel对比Info/Information"""
    return {
        "dall_e_3": {
            "quality": "高",
            "creativity": "高",
            "prompt_following": "优秀",
            "safety": "高",
            "max_images_per_request": 1,
            "supported_sizes": ["1024x1024", "1792x1024", "1024x1792"],
            "quality_options": ["standard", "hd"],
            "prompt_optimization": "自动优化",
            "cost": "较高"
        },
        "dall_e_2": {
            "quality": "中等",
            "creativity": "中等", 
            "prompt_following": "良好",
            "safety": "中等",
            "max_images_per_request": 10,
            "supported_sizes": ["256x256", "512x512", "1024x1024"],
            "quality_options": ["standard"],
            "prompt_optimization": "无",
            "cost": "较低"
        },
        "recommendations": {
            "high_quality_art": "DALL-E-3 with HD quality",
            "batch_generation": "DALL-E-2",
            "cost_effective": "DALL-E-2",
            "creative_projects": "DALL-E-3",
            "simple_illustrations": "DALL-E-2"
        }
    }

@mcp.tool()
def get_prompt_tips():
    """Get/Fetch提示词优化建议"""
    return {
        "general_tips": [
            "Description要具体和Detailed",
            "Include/Contains艺术风格（如：油画、水彩、数字艺术）",
            "指定颜色、光照和氛围",
            "提及构图和视角",
            "避免版权内容和真实人物"
        ],
        "style_examples": [
            "photorealistic",
            "oil painting",
            "watercolor",
            "digital art",
            "anime style",
            "cartoon",
            "minimalist",
            "surreal",
            "abstract"
        ],
        "lighting_examples": [
            "soft lighting",
            "dramatic lighting",
            "golden hour",
            "neon lighting",
            "natural light",
            "studio lighting"
        ],
        "composition_examples": [
            "close-up",
            "wide shot",
            "bird's eye view",
            "low angle",
            "centered composition",
            "rule of thirds"
        ],
        "dall_e_3_features": [
            "自动优化提示词",
            "更好理解复杂Description",
            "改进的文字渲染",
            "更准确的手部绘制"
        ]
    }

@mcp.tool()
def get_api_info():
    """Get/Fetch图像生成APIInfo/Information"""
    return {
        "service": "OpenAI DALL-E API",
        "description": "AI图像生成服务",
        "models": ["DALL-E-3", "DALL-E-2"],
        "features": [
            "文本到图像生成",
            "图像编辑",
            "图像变体",
            "多种尺寸和质量"
        ],
        "supported_formats": "PNG",
        "max_prompt_length": "4000 characters",
        "image_expiry": "1 hour after generation",
        "rate_limits": {
            "dall_e_3": "5 requests per minute",
            "dall_e_2": "50 requests per minute"
        },
        "content_policy": "严格的内容安全政策",
        "api_key_required": True,
        "documentation": "https://platform.openai.com/docs/guides/images"
    }

if __name__ == "__main__":
    mcp.run() 