"""
调用火山引擎ARK API的示例
"""

from api_modules.ark_client import ArkClient, ArkMessage, APIError
from taskflow.logger import get_logger

logger = get_logger("api_modules.example")

def example_basic_chat():
    """示例1：基本文本对话"""
    logger.info("=" * 50)
    logger.info("示例1：基本文本对话")
    logger.info("=" * 50)
    
    # 初始化客户端（API密钥可以从环境变量或配置文件获取）
    client = ArkClient()
    
    # 创建用户消息
    message = ArkMessage(role="user")
    message.add_text("你好，请介绍一下你自己")
    
    try:
        # 发送聊天请求
        response = client.chat(
            messages=[message]
        )
        
        logger.info("响应:", response)
        
        # 提取文本响应
        text = client.get_response_text(response)
        if text:
            logger.info(f"AI回复: {text}")
            
    except APIError as e:
        logger.error(f"API错误: {e}")
    except Exception as e:
        logger.error(f"其他错误: {e}")


def example_chat_with_system_prompt():
    """示例2：使用系统提示词"""
    logger.info("\n" + "=" * 50)
    logger.info("示例2：使用系统提示词")
    logger.info("=" * 50)
    
    client = ArkClient()
    
    # 创建用户消息
    user_message = ArkMessage(role="user")
    user_message.add_text("请帮我写一首关于春天的诗")
    
    try:
        # 使用字符串形式的系统提示词
        response = client.chat(
            model="doubao-seed-1-6-251015",
            messages=[user_message],
            system_prompt="你是一位专业的诗人，擅长写优美的诗歌"
        )
        
        logger.info("响应:", response)
        text = client.get_response_text(response)
        if text:
            logger.info(f"AI回复: {text}")
            
    except APIError as e:
        logger.error(f"API错误: {e}")


def example_multimodal_chat():
    """示例3：多模态对话（文本+图片）"""
    logger.info("\n" + "=" * 50)
    logger.info("示例3：多模态对话（文本+图片）")
    logger.info("=" * 50)
    
    client = ArkClient()
    
    # 创建包含图片和文本的用户消息
    user_message = ArkMessage(role="user")
    user_message.add_text("图片1中是否含有目标人物")
    user_message.add_image("https://ark-project.tos-cn-beijing.volces.com/doc_image/scene_01.png")
    user_message.add_text("图片2中是否含有目标人物")
    user_message.add_image("https://ark-project.tos-cn-beijing.volces.com/doc_image/scene_02.png")
    
    # 创建系统提示词（也支持多模态）
    system_message = ArkMessage(role="system")
    system_message.add_text("下面人物是目标人物")
    system_message.add_image("https://ark-project.tos-cn-beijing.volces.com/doc_image/target.png")
    system_message.add_text("请确认下面图片中是否含有目标人物")
    
    try:
        response = client.chat(
            model="doubao-seed-1-6-251015",
            messages=[user_message],
            system_prompt=system_message
        )
        
        logger.info("响应:", response)
        text = client.get_response_text(response)
        if text:
            logger.info(f"AI回复: {text}")
            
    except APIError as e:
        logger.error(f"API错误: {e}")


def example_chat_simple():
    """示例4：使用简化的chat_simple接口"""
    logger.info("\n" + "=" * 50)
    logger.info("示例4：使用简化的chat_simple接口")
    logger.info("=" * 50)
    
    client = ArkClient()
    
    try:
        # 仅文本
        response = client.chat_simple(
            model="doubao-seed-1-6-251015",
            text="今天天气怎么样？"
        )
        logger.info("仅文本响应:", response)
        
        # 文本+图片
        response = client.chat_simple(
            model="doubao-seed-1-6-251015",
            text="你看见了什么？",
            image_url="https://ark-project.tos-cn-beijing.volces.com/doc_image/scene_01.png"
        )
        logger.info("文本+图片响应:", response)
        
        # 带系统提示词
        response = client.chat_simple(
            model="doubao-seed-1-6-251015",
            text="分析这张图片",
            image_url="https://example.com/image.png",
            system_prompt="你是一个专业的图像分析助手"
        )
        logger.info("带系统提示词响应:", response)
        
    except APIError as e:
        logger.error(f"API错误: {e}")


def example_multiple_messages():
    """示例5：多轮对话"""
    logger.info("\n" + "=" * 50)
    logger.info("示例5：多轮对话")
    logger.info("=" * 50)
    
    client = ArkClient()
    
    # 创建多轮对话消息
    messages = [
        ArkMessage(role="user"),
        ArkMessage(role="user"),
        ArkMessage(role="user")
    ]
    
    messages[0].add_text("我的名字是张三")
    messages[1].add_text("我今年25岁")
    messages[2].add_text("请记住我的信息")
    
    try:
        response = client.chat(
            model="doubao-seed-1-6-251015",
            messages=messages,
            system_prompt="你是一个友好的助手，会记住用户提供的信息"
        )
        
        print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
        print(response)
        text = client.get_response_text(response)
        if text:
            logger.info(f"AI回复: {text}")
            
    except APIError as e:
        logger.error(f"API错误: {e}")


def example_dict_format():
    """示例6：使用字典格式的消息"""
    logger.info("\n" + "=" * 50)
    logger.info("示例6：使用字典格式的消息")
    logger.info("=" * 50)
    
    client = ArkClient()
    
    # 使用字典格式的消息（直接对应API格式）
    messages = [
        {
            "role": "system",
            "content": [
                {"type": "input_text", "text": "你是一个专业的助手"}
            ]
        },
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": "你好"},
                {
                    "type": "input_image",
                    "image_url": "https://example.com/image.png"
                }
            ]
        }
    ]
    
    try:
        response = client.chat(
            model="doubao-seed-1-6-251015",
            messages=messages
        )
        
        logger.info("响应:", response)
        
    except APIError as e:
        logger.error(f"API错误: {e}")


def example_error_handling():
    """示例7：错误处理"""
    logger.info("\n" + "=" * 50)
    logger.info("示例7：错误处理")
    logger.info("=" * 50)
    
    try:
        # 使用无效的API密钥
        client = ArkClient()
        
        message = ArkMessage(role="user")
        message.add_text("测试")
        
        response = client.chat(
            model="doubao-seed-1-6-251015",
            messages=[message]
        )
        
    except APIError as e:
        logger.error(f"捕获到API错误:")
        logger.error(f"  消息: {e.message}")
        logger.error(f"  状态码: {e.status_code}")
        logger.error(f"  响应: {e.response}")
    except ValueError as e:
        logger.error(f"参数错误: {e}")
    except Exception as e:
        logger.error(f"其他错误: {e}")


def example_context_manager():
    """示例8：使用上下文管理器"""
    logger.info("\n" + "=" * 50)
    logger.info("示例8：使用上下文管理器")
    logger.info("=" * 50)
    
    # 使用with语句自动管理资源
    with ArkClient() as client:
        message = ArkMessage(role="user")
        message.add_text("你好")
        
        try:
            response = client.chat(
                model="doubao-seed-1-6-251015",
                messages=[message]
            )
            logger.info("响应:", response)
        except APIError as e:
            logger.error(f"API错误: {e}")
    # 客户端会自动关闭


if __name__ == "__main__":
    # 注意：运行前请设置正确的API密钥
    # 方式1：通过环境变量设置
    # import os
    # os.environ["ARK_API_KEY"] = "your_api_key_here"
    
    # 方式2：直接在代码中传入（不推荐用于生产环境）
    # client = ArkClient(api_key="your_api_key_here")
    
    logger.info("火山引擎ARK API使用示例")
    logger.info("注意：请先设置正确的API密钥才能运行这些示例\n")
    
    # 取消注释以运行相应的示例
    # example_basic_chat()
    # example_chat_with_system_prompt()
    # example_multimodal_chat()
    # example_chat_simple()
    example_multiple_messages()
    # example_dict_format()
    # example_error_handling()
    # example_context_manager()
    
    logger.info("\n提示：取消注释上面的示例函数调用来运行示例")
