package config

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

type modelsFile struct {
	Default string            `yaml:"default"`
	Skills  map[string]string `yaml:"skills"`
}

type Models struct {
	data modelsFile
}

func LoadModels(path string) (Models, error) {
	raw, err := os.ReadFile(path)
	if err != nil {
		return Models{}, fmt.Errorf("load models: %w", err)
	}
	var f modelsFile
	if err := yaml.Unmarshal(raw, &f); err != nil {
		return Models{}, fmt.Errorf("parse models: %w", err)
	}
	return Models{data: f}, nil
}

// Resolve returns the model for a skill, respecting three-layer priority:
// 1. override (from MCP call) — highest
// 2. per-skill default from models.yaml
// 3. global default
func (m Models) Resolve(skill, override string) string {
	if override != "" {
		return override
	}
	if model, ok := m.data.Skills[skill]; ok {
		return model
	}
	return m.data.Default
}
