// Command security-center-mcp is the MCP server for Security Center.
//
// It speaks the MCP protocol over stdio: stdout carries only JSON-RPC
// protocol frames, all logging goes to stderr. Client setup (Claude
// Desktop, Cursor) is documented in docs/client-setup.md.
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"

	"github.com/modelcontextprotocol/go-sdk/jsonrpc"
	"github.com/modelcontextprotocol/go-sdk/mcp"

	"security-center-mcp/internal/config"
	"security-center-mcp/internal/server"
)

// errServerClosing matches the SDK's (unexported) ErrServerClosing by
// its wire code; it is returned when stdin closes mid-session, i.e.
// the client went away — a normal shutdown for a stdio server, not a
// failure.
var errServerClosing = &jsonrpc.Error{Code: -32004}

func main() {
	cfg, err := config.Load()
	if err != nil {
		fmt.Fprintf(os.Stderr, "security-center-mcp: %v\n", err)
		os.Exit(1)
	}

	fmt.Fprintf(os.Stderr, "security-center-mcp: serving MCP over stdio (base URL %s, API key %s)\n",
		cfg.BaseURL, cfg.MaskedAPIKey())

	err = server.New(*cfg).Run(context.Background(), &mcp.StdioTransport{})
	switch {
	case err == nil, errors.Is(err, io.EOF), errors.Is(err, errServerClosing):
		// Client disconnected (stdin closed): clean exit.
	default:
		fmt.Fprintf(os.Stderr, "security-center-mcp: %v\n", err)
		os.Exit(1)
	}
}
