package locationregistry

import (
	"fmt"
	"io/fs"
	"sync"

	rootassets "gitea.maximumdirect.net/eric/notarius/assets"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/llm"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/promptfs"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
)

const promptAssetRoot = "assets/prompts"

var promptAssetManifest = shared.PromptAssetManifest{
	ModuleDir: PromptID,
	ModuleFiles: []promptfs.ModulePromptFile{
		{Name: "prompt.yaml", Path: "prompts/prompt.yaml"},
		{Name: "instructions.md", Path: "prompts/instructions.md"},
		{Name: "candidates.md", Path: "prompts/candidates.md"},
	},
	SharedFiles: []string{"common-dnd-system.md", "common-dnd-entity-reconciliation.md", "common-dnd-transcript-windows.md"},
}

func moduleAssetFS() (fs.FS, error) {
	assets, err := fs.Sub(rootassets.FS(), "dnd/location-registry/normalize")
	if err != nil {
		return nil, fmt.Errorf("scope location normalization assets: %w", err)
	}
	return assets, nil
}

func RegisterPromptAssets(registry *llm.AssetRegistry) error {
	assets, err := moduleAssetFS()
	if err != nil {
		return err
	}
	promptFS, err := promptAssetManifest.PromptFS(assets)
	if err != nil {
		return fmt.Errorf("prepare location normalization prompt assets: %w", err)
	}
	return registry.RegisterPromptFS(promptFS, promptAssetRoot)
}

func promptAssetMetadata() (string, error) {
	promptAssetHashOnce.Do(func() {
		assets, err := moduleAssetFS()
		if err != nil {
			promptAssetHashErr = err
			return
		}
		promptAssetHash, promptAssetHashErr = promptAssetManifest.Hash(assets)
	})
	return promptAssetHash, promptAssetHashErr
}

var (
	promptAssetHashOnce sync.Once
	promptAssetHash     string
	promptAssetHashErr  error
)
