package packs

import (
	"fmt"
	"strings"
)

// RuntimeDeclaredFieldKeysFromObjectSpecPayloads returns the canonical
// lower-cased object.field keys that the current source still declares through
// its runtime object-spec surface, including injected system fields and derived
// discriminator companions.
func RuntimeDeclaredFieldKeysFromObjectSpecPayloads(payloads [][]byte, source string) (map[string]bool, error) {
	specs, err := ParseObjectSpecsPayloads(payloads, source)
	if err != nil {
		return nil, fmt.Errorf("parse object specs: %w", err)
	}
	defs, err := tableDefinitionsForObjectSpecs(specs)
	if err != nil {
		return nil, fmt.Errorf("build table definitions: %w", err)
	}
	expected := make(map[string]bool)
	for _, def := range defs {
		objectAPIName := strings.TrimSpace(def.TableName)
		if objectAPIName == "" {
			continue
		}
		for _, col := range def.Columns {
			fieldAPIName := strings.TrimSpace(col.Name)
			if !packColumnRequiresFieldMetadata(fieldAPIName) {
				continue
			}
			expected[strings.ToLower(objectAPIName+"."+fieldAPIName)] = true
		}
	}
	return expected, nil
}
