#!/usr/bin/env python3
"""Gitea MCP Server — exposes Gitea operations as MCP tools.

Runs over stdio. All tools authenticate via macOS keychain (git credential fill).
"""
import os
import sys

if "PYTEST_CURRENT_TEST" not in os.environ:
    sys.stderr = open("/tmp/mcp_server_stderr.log", "a", buffering=1)
sys.stderr.write(f"\n--- MCP SERVER STARTUP (PID {os.getpid()}) ---\n")

from role_session_router import (
    python_bytes_have_conflict_markers,
    skip_python_scan_walk_root,
)


# Startup health check: scan all python files in the Gitea-Tools directory for unresolved conflict markers.
def check_conflict_markers():
    dir_path = os.path.dirname(os.path.abspath(__file__))
    for root, dirs, files in os.walk(dir_path):
        if skip_python_scan_walk_root(dir_path, root):
            continue
        for file in files:
            if file.endswith(".py"):
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, "rb") as f:
                        if python_bytes_have_conflict_markers(f.read()):
                            rel_path = os.path.relpath(file_path, dir_path)
                            print(
                                f"infra_stop: Unresolved merge conflict detected in {rel_path}. "
                                "Please resolve all conflicts manually, finish/abort the merge, "
                                "restart the MCP server, and retry.",
                                file=sys.stderr
                            )
                            sys.exit(1)
                except Exception:
                    pass

check_conflict_markers()

# #558 / #695: claim the official entrypoint before loading mutation modules.
# This alone does NOT authorize mutations — gitea_mcp_server binds the live
# native MCP transport (stdio) immediately before mcp.run. Import-only or
# offline launch without that bind fails closed on mutations.
try:
    import mcp_daemon_guard

    mcp_daemon_guard.mark_sanctioned_daemon()
except Exception:
    # Guard import failures must not hide conflict-marker infra_stop above;
    # gitea_mcp_server main also marks + binds when run as __main__.
    pass

# Execute the actual server logic via exec in this namespace.
impl_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gitea_mcp_server.py")
try:
    with open(impl_path, "rb") as f:
        # Override __file__ global so that inspect.getsource(mcp_server) returns the implementation source
        globals()["__file__"] = impl_path
        code = compile(f.read(), impl_path, "exec")
        exec(code, globals())
except Exception as e:
    if isinstance(e, SyntaxError):
        # Fallback if a syntax error/conflict marker was introduced in gitea_mcp_server.py
        print(
            f"infra_stop: Unresolved merge conflict or syntax error in gitea_mcp_server.py. "
            "Please resolve all conflicts manually, finish/abort the merge, "
            "restart the MCP server, and retry.",
            file=sys.stderr
        )
        sys.exit(1)
    raise e
