import os
import sys
import httpx
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("SparkPool")

API_URL = os.environ.get("SPARKPOOL_API_URL", "http://47.97.184.52")
API_TOKEN = os.environ.get("SPARKPOOL_API_TOKEN")

@mcp.tool()
async def submit_roast(title: str, content: str, category: str = "life") -> str:
    """
    提交吐槽 (Roast).
    Args:
        title: 标题
        content: 内容 (建议使用中文)
        category: 分类 (life: 生活, work: 工作, tech: 科技, other: 其他)
    """
    if not API_TOKEN:
        return "Error: SPARKPOOL_API_TOKEN not configured."
    
    async with httpx.AsyncClient() as client:
        headers = {
            "X-MCP-Token": API_TOKEN,
            "Content-Type": "application/json"
        }
        # Simplify category mapping if needed, user provided string
        payload = {
            "title": title,
            "content": content,
            "category": category,
            "status": "published"
        }
        try:
            resp = await client.post(f"{API_URL}/api/v1/roasts", json=payload, headers=headers)
            if resp.status_code >= 400:
                return f"Error: {resp.status_code} - {resp.text}"
            data = resp.json()
            return f"Roast submitted successfully! ID: {data['data']['id']}"
        except Exception as e:
            return f"Error submitting roast: {str(e)}"

@mcp.tool()
async def submit_idea(
    title: str, 
    summary: str, 
    category: str = "其他",
    sale_mode: str = "public_free", 
    price_points: int = 0
) -> str:
    """
    提交构思/点子 (Idea). 
    Idea无需经过AI检查，直接入库。
    Args:
        title: 标题
        summary: 简介/内容 (建议使用中文)
        category: 分类 (建议: 科技, 生活, 娱乐, 其他)
        sale_mode: 售卖模式 (public_free: 免费公开, paid_shared: 付费共享, exclusive_transfer: 独家转让)
        price_points: 价格 (积分), 免费模式填0
    """
    if not API_TOKEN:
        return "Error: SPARKPOOL_API_TOKEN not configured."
        
    async with httpx.AsyncClient() as client:
        headers = {
            "X-MCP-Token": API_TOKEN,
            "Content-Type": "application/json"
        }
        
        payload = {
            "title": title,
            "summary": summary,
            "content_markdown": summary,
            "domain": category,
            "category": category,
            "sale_mode": sale_mode,
            "price_points": price_points,
            "tags": ["MCP", "Agent"]
        }
        try:
            resp = await client.post(f"{API_URL}/api/v1/ideas", json=payload, headers=headers)
            if resp.status_code >= 400:
                print(f"Failed response: {resp.text}")
                return f"Error: {resp.status_code} - {resp.text}"
            data = resp.json()
            return f"Idea submitted successfully! ID: {data['data']['id']}"
        except Exception as e:
             return f"Error submitting idea: {str(e)}"

def main():
    if not API_TOKEN:
         print("Warning: SPARKPOOL_API_TOKEN is not set.", file=sys.stderr)
    mcp.run()

if __name__ == "__main__":
    main()
