package maximizer

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
)

const defaultConstraintFile = "policies/maximizer_constraints_v1.json"

// LoadConstraintRules reads a constraint ruleset from a JSON file.
func LoadConstraintRules(path string) (*ConstraintRuleSet, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read constraint file %s: %w", path, err)
	}
	var rs ConstraintRuleSet
	if err := json.Unmarshal(data, &rs); err != nil {
		return nil, fmt.Errorf("parse constraint file %s: %w", path, err)
	}
	if rs.Version == "" {
		return nil, fmt.Errorf("constraint file %s: missing version", path)
	}
	return &rs, nil
}

// LoadConstraintRulesFromDefault loads from the default policy file
// relative to the project root.
func LoadConstraintRulesFromDefault() (*ConstraintRuleSet, error) {
	root := findProjectRoot()
	path := filepath.Join(root, defaultConstraintFile)
	return LoadConstraintRules(path)
}

// findProjectRoot walks up from the current source file to find the
// ai-compliance-sdk root (contains go.mod or policies/).
func findProjectRoot() string {
	_, filename, _, ok := runtime.Caller(0)
	if !ok {
		return "."
	}
	dir := filepath.Dir(filename)
	for i := 0; i < 10; i++ {
		if _, err := os.Stat(filepath.Join(dir, "policies")); err == nil {
			return dir
		}
		dir = filepath.Dir(dir)
	}
	return "."
}
