// Package config loads and validates runtime configuration for the
// Security Center MCP server.
package config

import (
	"fmt"
	"os"
)

const (
	// EnvBaseURL points to the Security Center backend API.
	EnvBaseURL = "SECURITY_CENTER_BASE_URL"
	// EnvAPIKey is the API key used to authenticate against the backend.
	EnvAPIKey = "SECURITY_CENTER_API_KEY"

	// DefaultBaseURL is used when EnvBaseURL is not set.
	DefaultBaseURL = "http://127.0.0.1:8080"

	// MinAPIKeyLength is the minimum accepted API key length. Keys issued
	// by Security Center look like "sc_..." and are much longer; anything
	// shorter is treated as a configuration mistake.
	MinAPIKeyLength = 16

	// maskPrefixLen is how many leading API key characters may be shown
	// in logs and banners.
	maskPrefixLen = 12
)

// Config holds the MCP server runtime configuration.
type Config struct {
	BaseURL string
	APIKey  string
}

// Load reads configuration from the process environment and validates it.
func Load() (*Config, error) {
	baseURL := os.Getenv(EnvBaseURL)
	if baseURL == "" {
		baseURL = DefaultBaseURL
	}

	apiKey := os.Getenv(EnvAPIKey)
	if err := validateAPIKey(apiKey); err != nil {
		return nil, err
	}

	return &Config{BaseURL: baseURL, APIKey: apiKey}, nil
}

func validateAPIKey(key string) error {
	if key == "" {
		return fmt.Errorf("%s is required — 用你自己的 key 启动（在 Security Center 前端 API Keys 页创建）", EnvAPIKey)
	}
	if len(key) < MinAPIKeyLength {
		return fmt.Errorf("%s is too short (got %d chars, need at least %d)", EnvAPIKey, len(key), MinAPIKeyLength)
	}
	return nil
}

// MaskedAPIKey returns the API key with only its first 12 characters
// visible, safe for logging.
func (c *Config) MaskedAPIKey() string {
	if len(c.APIKey) <= maskPrefixLen {
		return c.APIKey
	}
	return c.APIKey[:maskPrefixLen] + "..."
}
