package tenants

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

// ReadFile loads the tenant list at path.
//
// The format is detected from the first non-whitespace byte: '[' or '{'
// triggers JSON parsing, otherwise the file is treated as plain text. An
// empty file returns an empty slice (not nil).
func ReadFile(path string) ([]string, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	raw := strings.TrimSpace(string(data))
	if raw == "" {
		return []string{}, nil
	}
	if raw[0] == '[' || raw[0] == '{' {
		return parseJSON(path, raw)
	}
	return parseText(raw), nil
}

func parseJSON(path, raw string) ([]string, error) {
	var v any
	if err := json.Unmarshal([]byte(raw), &v); err != nil {
		return nil, fmt.Errorf("%s: %w", path, err)
	}
	var arr []any
	switch x := v.(type) {
	case []any:
		arr = x
	case map[string]any:
		arr, _ = x["tenants"].([]any)
	}
	if arr == nil {
		return nil, fmt.Errorf("%s: expected JSON object with a 'tenants' array or a JSON array", path)
	}
	out := make([]string, 0, len(arr))
	for _, item := range arr {
		switch y := item.(type) {
		case string:
			out = append(out, y)
		case map[string]any:
			if t, ok := y["tenant"].(string); ok {
				out = append(out, t)
			}
		}
	}
	return out, nil
}

func parseText(raw string) []string {
	out := []string{}
	for line := range strings.SplitSeq(raw, "\n") {
		trim := strings.TrimSpace(line)
		if trim == "" || strings.HasPrefix(trim, "#") {
			continue
		}
		out = append(out, trim)
	}
	return out
}
