"""MCP Server 主程序."""

import asyncio
import json
import os
import platform
from pathlib import Path
from typing import Any

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool

from .docx_generator import generate_thesis_docx
from .formats import get_format, list_formats
from .markdown_parser import parse_markdown_thesis


def get_desktop_path() -> str:
    """获取系统桌面路径，支持 Windows 和 macOS/Linux."""
    system = platform.system()
    
    if system == "Windows":
        # Windows: 使用 USERPROFILE 环境变量
        desktop = Path.home() / "Desktop"
    elif system == "Darwin":
        # macOS
        desktop = Path.home() / "Desktop"
    else:
        # Linux 和其他系统
        desktop = Path.home() / "Desktop"
        # 如果 Desktop 不存在，尝试使用 XDG 标准
        if not desktop.exists():
            xdg_desktop = os.environ.get("XDG_DESKTOP_DIR", "")
            if xdg_desktop:
                desktop = Path(xdg_desktop)
            else:
                # 默认使用用户主目录
                desktop = Path.home()
    
    return str(desktop)


def resolve_output_path(output_path: str | None, output_dir: str | None = None) -> str:
    """解析输出路径.
    
    Args:
        output_path: 用户指定的完整路径或文件名
        output_dir: 用户指定的输出目录（可选）
        
    Returns:
        完整的输出文件路径
    """
    # 如果提供了 output_path
    if output_path:
        path = Path(output_path)
        
        # 检查是否是绝对路径（跨平台兼容）
        # Windows: C:\path 或 \\server\share
        # Unix: /path
        is_absolute = False
        if platform.system() == "Windows":
            # Windows: 检查是否有盘符或是否是 UNC 路径
            is_absolute = bool(path.drive) or str(path).startswith('\\\\')
        else:
            # Unix/Linux/macOS: 以 / 开头
            is_absolute = str(path).startswith('/')
        
        if is_absolute:
            # 是绝对路径，直接使用
            return str(path)
        else:
            # 是相对路径或只有文件名
            if output_dir:
                return str(Path(output_dir) / path.name)
            else:
                return str(Path(get_desktop_path()) / path.name)
    
    # 如果没有提供 output_path，但有 output_dir，使用默认文件名
    if output_dir:
        return str(Path(output_dir) / "论文.docx")
    
    # 默认使用桌面路径和默认文件名
    return str(Path(get_desktop_path()) / "论文.docx")

# 创建 MCP Server
app = Server("docx-thesis-server")


@app.list_tools()
async def list_tools() -> list[Tool]:
    """列出所有可用工具."""
    return [
        Tool(
            name="generate_thesis",
            description="生成标准格式的论文 DOCX 文件。支持中山大学、华南师范大学等多所高校的论文格式。",
            inputSchema={
                "type": "object",
                "properties": {
                    "markdown_content": {
                        "type": "string",
                        "description": "论文的 Markdown 内容，包含标题、摘要、章节、参考文献等",
                    },
                    "university": {
                        "type": "string",
                        "description": "大学模板代码，如 'sysu'(中山大学)、'scnu'(华南师范大学)、'generic'(通用格式)",
                        "enum": ["sysu", "scnu", "generic"],
                        "default": "generic",
                    },
                    "output_path": {
                        "type": "string",
                        "description": "输出文件路径或文件名，如 'thesis.docx' 或 '/path/to/thesis.docx'。如果只提供文件名，将保存到 output_dir 或系统桌面",
                    },
                    "output_dir": {
                        "type": "string",
                        "description": "输出目录路径，如 '/path/to/output' 或 'C:\\Users\\Name\\Documents'。默认为系统桌面",
                    },
                    "metadata": {
                        "type": "object",
                        "description": "论文元数据",
                        "properties": {
                            "title": {"type": "string", "description": "论文标题"},
                            "author": {"type": "string", "description": "作者姓名"},
                            "student_id": {"type": "string", "description": "学号"},
                            "major": {"type": "string", "description": "专业"},
                            "college": {"type": "string", "description": "学院"},
                            "advisor": {"type": "string", "description": "指导教师"},
                            "date": {"type": "string", "description": "日期，如 '2025年3月'"},
                        },
                    },
                },
                "required": ["markdown_content", "output_path"],
            },
        ),
        Tool(
            name="list_universities",
            description="列出所有支持的大学论文模板",
            inputSchema={"type": "object", "properties": {}},
        ),
        Tool(
            name="get_university_format",
            description="获取指定大学的格式要求详情",
            inputSchema={
                "type": "object",
                "properties": {
                    "university": {
                        "type": "string",
                        "description": "大学模板代码，如 'sysu'(中山大学)、'scnu'(华南师范大学)",
                        "enum": ["sysu", "scnu", "generic"],
                    }
                },
                "required": ["university"],
            },
        ),
    ]


@app.call_tool()
async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:
    """调用工具."""
    if name == "generate_thesis":
        return await _generate_thesis(arguments)
    elif name == "list_universities":
        return await _list_universities()
    elif name == "get_university_format":
        return await _get_university_format(arguments)
    else:
        raise ValueError(f"未知工具: {name}")


async def _generate_thesis(arguments: dict[str, Any]) -> list[TextContent]:
    """生成论文."""
    try:
        markdown_content = arguments["markdown_content"]
        university = arguments.get("university", "generic")
        output_path_input = arguments.get("output_path")
        output_dir_input = arguments.get("output_dir")
        metadata_override = arguments.get("metadata", {})
        
        # 解析输出路径
        output_path = resolve_output_path(output_path_input, output_dir_input)

        # 解析 Markdown
        content = parse_markdown_thesis(markdown_content)

        # 应用元数据覆盖
        for key, value in metadata_override.items():
            if hasattr(content.metadata, key) and value:
                setattr(content.metadata, key, value)

        # 获取格式配置
        format_config = get_format(university)

        # 生成 DOCX
        generate_thesis_docx(content, format_config, output_path)

        # 构建结果信息
        sections_count = len(content.sections)
        refs_count = len(content.references)

        result = {
            "success": True,
            "message": "论文生成成功！",
            "output_path": output_path,
            "university": university,
            "university_name": format_config.description,
            "statistics": {
                "sections_count": sections_count,
                "references_count": refs_count,
                "has_abstract_cn": bool(content.metadata.abstract_cn),
                "has_abstract_en": bool(content.metadata.abstract_en),
            },
        }

        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False, indent=2))]

    except Exception as e:
        error_result = {"success": False, "error": str(e), "message": f"生成论文时出错: {str(e)}"}
        return [
            TextContent(type="text", text=json.dumps(error_result, ensure_ascii=False, indent=2))
        ]


async def _list_universities() -> list[TextContent]:
    """列出所有支持的大学."""
    formats = list_formats()

    universities = []
    for code, description in formats.items():
        universities.append(
            {
                "code": code,
                "name": description,
                "example_usage": f'generate_thesis with university="{code}"',
            }
        )

    result = {"universities": universities, "total": len(universities)}

    return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False, indent=2))]


async def _get_university_format(arguments: dict[str, Any]) -> list[TextContent]:
    """获取大学格式详情."""
    try:
        university = arguments["university"]
        format_config = get_format(university)

        result = {
            "code": university,
            "name": format_config.description,
            "page_settings": {
                "page_size": "A4",
                "top_margin_cm": format_config.page.top_margin,
                "bottom_margin_cm": format_config.page.bottom_margin,
                "left_margin_cm": format_config.page.left_margin,
                "right_margin_cm": format_config.page.right_margin,
            },
            "font_settings": {
                "title": f"{format_config.title_font.name} {format_config.title_font.size}pt",
                "heading1": f"{format_config.heading1_font.name} {format_config.heading1_font.size}pt",
                "heading2": f"{format_config.heading2_font.name} {format_config.heading2_font.size}pt",
                "body": f"{format_config.body_font.name} {format_config.body_font.size}pt",
            },
            "paragraph_settings": {
                "line_spacing": format_config.body_paragraph.line_spacing,
                "first_line_indent_chars": format_config.body_paragraph.first_line_indent,
            },
            "features": {
                "has_cover_page": format_config.has_cover_page,
                "has_toc": format_config.has_toc,
                "toc_levels": format_config.toc_levels,
            },
        }

        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False, indent=2))]

    except Exception as e:
        error_result = {"error": str(e), "message": f"获取格式信息时出错: {str(e)}"}
        return [
            TextContent(type="text", text=json.dumps(error_result, ensure_ascii=False, indent=2))
        ]


async def main() -> None:
    """主程序入口."""
    async with stdio_server() as (read_stream, write_stream):
        await app.run(read_stream, write_stream, app.create_initialization_options())


if __name__ == "__main__":
    asyncio.run(main())
