package services

import (
	"os"
	"path/filepath"
	"testing"
)

func TestListNpmExtensions(t *testing.T) {
	agentDir := t.TempDir()
	npmRoot := filepath.Join(agentDir, "npm", "node_modules", "pi-subagents")
	if err := os.MkdirAll(npmRoot, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(npmRoot, "package.json"), []byte(`{"name":"pi-subagents","version":"0.28.0"}`), 0o644); err != nil {
		t.Fatal(err)
	}
	settings := `{
		"packages": ["npm:pi-subagents", {"source": "npm:pi-mcp-adapter@2.10.0"}]
	}`
	if err := os.WriteFile(filepath.Join(agentDir, "settings.json"), []byte(settings), 0o644); err != nil {
		t.Fatal(err)
	}

	exts := listNpmExtensions(agentDir)
	if len(exts) != 2 {
		t.Fatalf("expected 2 npm extensions, got %d", len(exts))
	}

	found := map[string]modelsExtensionSnapshot{}
	for _, ext := range exts {
		found[ext.Name] = modelsExtensionSnapshot{
			Version:    ext.Version,
			Category:   ext.Category,
			Toggleable: ext.Toggleable,
			Source:     ext.Source,
		}
	}

	if found["pi-subagents"].Version != "0.28.0" {
		t.Fatalf("pi-subagents version: %#v", found["pi-subagents"])
	}
	if found["pi-subagents"].Category != "npm" || found["pi-subagents"].Toggleable {
		t.Fatalf("pi-subagents metadata: %#v", found["pi-subagents"])
	}
	if found["pi-mcp-adapter"].Source != "npm:pi-mcp-adapter@2.10.0" {
		t.Fatalf("pi-mcp-adapter source: %#v", found["pi-mcp-adapter"])
	}
}

type modelsExtensionSnapshot struct {
	Version    string
	Category   string
	Toggleable bool
	Source     string
}
