// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: LicenseRef-MutuaL-1.2

// Package config holds configuration for the SilverBullet MCP server,
// loaded from environment variables and command-line flags.
package config

import (
	"fmt"
	"net/url"
	"os"
	"strconv"
)

// Config holds all configuration for the sb-mcp server.
type Config struct {
	// SBURL is the base URL of the SilverBullet instance (required).
	SBURL string
	// SBUser and SBPass are Basic Auth credentials (optional).
	SBUser string
	SBPass string
	// SBToken is a Bearer token for authentication (optional).
	SBToken string
	// HTTPAddr is the address for streamable HTTP transport.
	// Empty string means stdio transport.
	HTTPAddr string
	// DefaultTimeout is the default Lua execution timeout in seconds.
	DefaultTimeout int
}

// Load reads configuration from environment variables.
// SB_URL (required), SB_USER, SB_PASS, SB_TOKEN (optional).
func Load() (*Config, error) {
	sbURL := os.Getenv("SB_URL")
	if sbURL == "" {
		return nil, fmt.Errorf("SB_URL environment variable is required")
	}

	u, err := url.Parse(sbURL)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
		return nil, fmt.Errorf("SB_URL must be a valid HTTP(S) URL, got: %s", sbURL)
	}

	cfg := &Config{
		SBURL:          sbURL,
		SBUser:         os.Getenv("SB_USER"),
		SBPass:         os.Getenv("SB_PASS"),
		SBToken:        os.Getenv("SB_TOKEN"),
		DefaultTimeout: parseDefaultTimeout(),
	}

	return cfg, nil
}

// HasBasicAuth returns true if both SB_USER and SB_PASS are set.
func (c *Config) HasBasicAuth() bool {
	return c.SBUser != "" && c.SBPass != ""
}

// HasBearerToken returns true if SB_TOKEN is set.
func (c *Config) HasBearerToken() bool {
	return c.SBToken != ""
}

// parseDefaultTimeout reads the default Lua execution timeout from
// the SB_TIMEOUT environment variable (in seconds), defaulting to 120.
func parseDefaultTimeout() int {
	s := os.Getenv("SB_TIMEOUT")
	if s == "" {
		return 120
	}
	n, err := strconv.Atoi(s)
	if err != nil || n < 1 {
		return 120
	}
	return n
}
