package spells

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: "dnd.spells",
	ModuleFiles: []promptfs.ModulePromptFile{
		{Name: "prompt.yaml", Path: "prompts/prompt.yaml"},
		{Name: "spell-catalog.md", Path: "prompts/spell-catalog.md"},
		{Name: "instructions.md", Path: "prompts/instructions.md"},
	},
	SharedFiles: []string{
		"common-dnd-system.md",
		"common-dnd-extraction-evidence.md",
		"common-dnd-identity.md",
		"common-dnd-transcript-chunk.md",
		"common-dnd-references.md",
		"common-dnd-npc-registry.md",
	},
}

func moduleAssetFS() (fs.FS, error) {
	assets, err := fs.Sub(rootassets.FS(), "dnd/spells")
	if err != nil {
		return nil, fmt.Errorf("scope spell 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 spell 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 spell 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
)
