package config

import (
	"encoding/base64"
	"errors"
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

// ClientConfig holds raw YAML configuration values.
type ClientConfig struct {
	K1Base64  string `yaml:"k1_base64"`
	ServerURL string `yaml:"server_url"`
}

// LoadedClientConfig is a validated, decoded client config.
type LoadedClientConfig struct {
	KeyK1    []byte
	ServerURL string
}

// LoadClientConfig loads YAML config from the given path and validates fields.
func LoadClientConfig(path string) (*LoadedClientConfig, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read config: %w", err)
	}
	var raw ClientConfig
	if err := yaml.Unmarshal(data, &raw); err != nil {
		return nil, fmt.Errorf("unmarshal yaml: %w", err)
	}
	if raw.K1Base64 == "" {
		return nil, errors.New("k1_base64 is required")
	}
	keyK1, err := base64.StdEncoding.DecodeString(raw.K1Base64)
	if err != nil {
		return nil, fmt.Errorf("decode k1 base64: %w", err)
	}
	if len(keyK1) != 32 {
		return nil, fmt.Errorf("k1 must be 32 bytes, got %d", len(keyK1))
	}
	if raw.ServerURL == "" {
		return nil, errors.New("server_url is required")
	}
	return &LoadedClientConfig{KeyK1: keyK1, ServerURL: raw.ServerURL}, nil
}


