"""
OpenFlow MCP Tools - 自定义 MCP Server 入口

使用 FastMCP 快速定义工具，通过 stdio 协议与 MCP 客户端通信。
"""
from mcp.server.fastmcp import FastMCP

# 创建 MCP Server 实例
mcp = FastMCP(
    "OpenFlow Tools",
    description="OpenFlow 自定义 MCP 工具集，提供节假日查询、文本摘要、网页读取等能力"
)


# ============================================================
# 工具 1：中国节假日查询
# ============================================================
@mcp.tool()
async def get_holiday_info(year: int, month: int = 0) -> str:
    """
    查询中国法定节假日和调休安排。

    Args:
        year: 年份，如 2026
        month: 月份（1-12），0 表示查询全年
    """
    import httpx

    # 使用免费的节假日 API
    url = f"https://timor.tech/api/holiday/year/{year}"
    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.get(url)
            resp.raise_for_status()
            data = resp.json()

        if data.get("code") != 0:
            return f"查询失败: {data.get('msg', '未知错误')}"

        holidays = data.get("holiday", {})
        results = []

        for date_str, info in holidays.items():
            m = int(date_str.split("-")[0])
            if month and m != month:
                continue
            results.append(
                f"📅 {info['date']} {info['name']} "
                f"{'（放假）' if info['holiday'] else '（调休上班）'}"
                f"{' - ' + info.get('wage', '') if info.get('wage') else ''}"
            )

        if not results:
            return f"{year}年{'%d月' % month if month else ''}暂无节假日数据"

        return f"🇨🇳 {year}年{'%d月' % month if month else ''}节假日安排：\n\n" + "\n".join(results)

    except Exception as e:
        return f"查询节假日失败: {str(e)}"


# ============================================================
# 工具 2：文本摘要提取
# ============================================================
@mcp.tool()
async def text_summary(text: str, max_sentences: int = 3) -> str:
    """
    从一段文本中提取关键句子作为摘要。

    Args:
        text: 需要提取摘要的文本内容
        max_sentences: 最多提取的句子数量，默认 3
    """
    import re

    # 简单的基于句子的摘要提取
    sentences = re.split(r'[。！？.!?]+', text)
    sentences = [s.strip() for s in sentences if len(s.strip()) > 10]

    if not sentences:
        return "文本内容太短，无法提取摘要。"

    # 按长度和位置加权选择关键句
    scored = []
    for i, s in enumerate(sentences):
        score = len(s) * 0.3  # 长句更可能包含重要信息
        if i == 0:
            score *= 1.5  # 首句通常是核心
        if i == len(sentences) - 1:
            score *= 1.2  # 末句通常是总结
        scored.append((score, s))

    scored.sort(key=lambda x: x[0], reverse=True)
    selected = scored[:max_sentences]
    # 按原文顺序排列
    selected.sort(key=lambda x: sentences.index(x[1]))

    summary = "。".join(s[1] for s in selected) + "。"
    return f"📝 摘要（{len(selected)}句）:\n\n{summary}"


# ============================================================
# 工具 3：网页内容读取
# ============================================================
@mcp.tool()
async def url_reader(url: str) -> str:
    """
    读取指定 URL 的网页内容，返回纯文本。

    Args:
        url: 需要读取的网页 URL
    """
    import httpx
    import re

    try:
        async with httpx.AsyncClient(
            timeout=15,
            follow_redirects=True,
            headers={"User-Agent": "Mozilla/5.0 (compatible; OpenFlowBot/1.0)"}
        ) as client:
            resp = await client.get(url)
            resp.raise_for_status()
            html = resp.text

        # 简单的 HTML → 纯文本转换
        # 移除 script 和 style
        html = re.sub(r'<script[^>]*>.*?</script>', '', html, flags=re.DOTALL | re.IGNORECASE)
        html = re.sub(r'<style[^>]*>.*?</style>', '', html, flags=re.DOTALL | re.IGNORECASE)
        # 替换常见标签
        html = re.sub(r'<br\s*/?\s*>', '\n', html, flags=re.IGNORECASE)
        html = re.sub(r'<p[^>]*>', '\n', html, flags=re.IGNORECASE)
        html = re.sub(r'<div[^>]*>', '\n', html, flags=re.IGNORECASE)
        html = re.sub(r'<h[1-6][^>]*>', '\n## ', html, flags=re.IGNORECASE)
        # 移除所有其他标签
        text = re.sub(r'<[^>]+>', '', html)
        # 清理空白
        text = re.sub(r'\n{3,}', '\n\n', text)
        text = text.strip()

        # 限制长度
        if len(text) > 5000:
            text = text[:5000] + "\n\n...[内容已截断，共 %d 字]" % len(text)

        return f"🔗 {url}\n\n{text}"

    except Exception as e:
        return f"读取网页失败: {str(e)}"


# ============================================================
# 入口函数
# ============================================================
def main():
    """MCP Server 入口 - 通过 stdio 协议启动"""
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()
