package combat_semantics

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"},
	},
	SharedFiles: []string{
		"common-dnd-system.md",
		"common-dnd-scene-combat-policy.md",
		"common-dnd-transcript-chunk.md",
	},
}

func moduleAssetFS() (fs.FS, error) {
	assets, err := fs.Sub(rootassets.FS(), "dnd/scene-descriptions/validate/combat-semantics")
	if err != nil {
		return nil, fmt.Errorf("scope scene combat-semantics validator 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 scene combat-semantics validator prompt assets: %w", err)
	}
	if err := registry.RegisterPromptFS(promptFS, promptAssetRoot); err != nil {
		return err
	}
	schemas, err := fs.Sub(assets, "schemas")
	if err != nil {
		return fmt.Errorf("scope scene combat-semantics validator schemas: %w", err)
	}
	return registry.RegisterSchemaFS(schemas, ".")
}

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
)
