// Package config defines the TOML configuration schema for the <<project_name>>
// MCP server and a loader that applies defaults and returns typed errors.
//
// You normally do not edit this file. To change the listen address, port, MCP
// paths, or log level, edit config.toml — never the code.
package config

import (
	"fmt"
	"os"

	"github.com/BurntSushi/toml"
)

// Config is the root configuration: the MCP/Gin server (Server) and the
// structured logger (Log).
type Config struct {
	Server ServerConfig `toml:"server"`
	Log    LogConfig    `toml:"log"`
}

// ServerConfig holds the HTTP/MCP listener settings.
//
// Addr is the host:port the Gin engine listens on. McpPath is where the
// stateless streamable-HTTP MCP handler is mounted (also at the trailing-slash
// variant). SSEPath is where the classic SSE handler is mounted. TrustedProxyCIDRs
// lists the proxy networks gin trusts when resolving c.ClientIP() from
// X-Forwarded-For (empty -> trust loopback only).
type ServerConfig struct {
	Addr              string   `toml:"addr"`
	McpPath           string   `toml:"mcp_path"`
	SSEPath           string   `toml:"sse_path"`
	TrustedProxyCIDRs []string `toml:"trusted_proxy_cidrs"`
}

// LogConfig controls the zap logger level and renderer.
type LogConfig struct {
	Level  string `toml:"level"`
	Format string `toml:"format"`
}

// defaults returns a Config populated with the documented default values. Load
// decodes the TOML file over this base so unset fields keep their defaults while
// present fields override them.
func defaults() Config {
	return Config{
		Server: ServerConfig{
			Addr:              "<<default_host>>:<<default_port>>",
			McpPath:           "/mcp",
			SSEPath:           "/sse",
			TrustedProxyCIDRs: []string{},
		},
		Log: LogConfig{
			Level:  "info",
			Format: "console",
		},
	}
}

// Load reads the TOML config file at path over the documented defaults and
// returns the resulting Config. It returns a typed error (never panics) when the
// file cannot be read or parsed.
func Load(path string) (Config, error) {
	cfg := defaults()

	data, err := os.ReadFile(path)
	if err != nil {
		return Config{}, fmt.Errorf("config: read %q: %w", path, err)
	}

	if err := toml.Unmarshal(data, &cfg); err != nil {
		return Config{}, fmt.Errorf("config: parse %q: %w", path, err)
	}

	if cfg.Server.Addr == "" {
		return Config{}, fmt.Errorf("config: server.addr must not be empty")
	}

	return cfg, nil
}
