"""
SPOQ MCP Server entry point.

Registers all SPOQ tools and runs the FastMCP server via stdio transport.
On startup, checks for newer versions published at spoqpaper.com and warns
the user if an update is available.
"""

from __future__ import annotations

import json
import sys
from contextlib import asynccontextmanager
from pathlib import Path

from mcp.server.fastmcp import FastMCP

from spoq_server import __version__
from spoq_server.version_check import (
    VersionCheckResult,
    check_version,
    check_project_structure,
    warn_if_outdated,
)


def project_root() -> Path:
    """
    Find the project root by walking up from the current file to find .git directory.

    Returns the path to the repository root (where .git lives).
    """
    current = Path(__file__).resolve()
    for parent in current.parents:
        if (parent / ".git").exists():
            return parent
    # Fallback: assume 4 levels up from server.py
    # code/mcp/spoq-server/src/spoq_server/server.py -> project root
    return Path(__file__).resolve().parents[4]


# Module-level state populated by the lifespan hook.
_version_check_result: VersionCheckResult | None = None
_project_check_result: dict | None = None


@asynccontextmanager
async def lifespan(server: FastMCP):
    """Run startup tasks (version check, project structure check) and yield server context."""
    global _version_check_result, _project_check_result
    _version_check_result = check_version()
    warn_if_outdated(_version_check_result)
    _project_check_result = check_project_structure(project_root())
    if _project_check_result.get("needs_upgrade"):
        print(
            "[spoq] Project structure outdated. Run: spoq init --upgrade",
            file=sys.stderr,
        )
    yield {}


# Create FastMCP server instance with lifespan
mcp = FastMCP("spoq", lifespan=lifespan)


@mcp.tool()
def spoq_ping() -> str:
    """Health check - returns server version and project root path."""
    result = {
        "version": __version__,
        "project_root": str(project_root()),
        "package": "spoq",
        "status": "ok",
    }
    if _version_check_result and _version_check_result.is_outdated:
        result["update_available"] = _version_check_result.remote_version
        result["update_notice"] = (
            f"Update available: {_version_check_result.local_version} → "
            f"{_version_check_result.remote_version}. Run: pipx upgrade spoq"
        )
        result["package_update_command"] = "pipx upgrade spoq"
    if _project_check_result and _project_check_result.get("needs_upgrade"):
        result["project_needs_upgrade"] = True
        result["missing_structure"] = _project_check_result["missing"]
        result["upgrade_command"] = "spoq init --upgrade --target ."
        result["upgrade_instructions"] = (
            "Project structure is outdated. Missing: "
            + ", ".join(_project_check_result["missing"])
            + ". Run `spoq init --upgrade` to update."
        )
    return json.dumps(result)


# Import tool modules to register their tools with the mcp instance
import spoq_server.epic_tools  # noqa: F401, E402
import spoq_server.task_tools  # noqa: F401, E402
import spoq_server.team_tools  # noqa: F401, E402
import spoq_server.util_tools  # noqa: F401, E402
import spoq_server.map_tools  # noqa: F401, E402
import spoq_server.roadmap_tools  # noqa: F401, E402


def main():
    """Run the SPOQ MCP server."""
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()
