package skillbundle

import (
	"archive/zip"
	"bytes"
	"io"
	"slices"
	"strings"
	"testing"
)

func TestLoadMetadata(t *testing.T) {
	metadata, err := LoadMetadata()
	if err != nil {
		t.Fatalf("load metadata: %v", err)
	}
	if metadata.Name != Name || metadata.Version != "1.0.2" {
		t.Fatalf("unexpected metadata: %+v", metadata)
	}
	if !slices.Equal(metadata.Modules, []string{"model-runtime"}) {
		t.Fatalf("unexpected modules: %+v", metadata.Modules)
	}
	if FileName(metadata) != "ai-gateway-ops-management-v1.0.2.zip" {
		t.Fatalf("unexpected file name: %s", FileName(metadata))
	}
}

func TestBuildArchiveContainsOperationsSkill(t *testing.T) {
	raw, err := BuildArchive()
	if err != nil {
		t.Fatalf("build archive: %v", err)
	}
	archive, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
	if err != nil {
		t.Fatalf("open archive: %v", err)
	}
	files := make(map[string]*zip.File, len(archive.File))
	for _, file := range archive.File {
		files[file.Name] = file
		if strings.HasPrefix(file.Name, "/") || strings.Contains(file.Name, "..") {
			t.Fatalf("unsafe archive path: %q", file.Name)
		}
	}
	expected := []string{
		"SKILL.md",
		"agents/openai.yaml",
		"skill.json",
		"references/api-discovery-and-safety.md",
		"references/model-providers-and-base-models.md",
		"references/model-pricing-and-policies.md",
		"references/model-billing-configuration-and-estimation.md",
		"references/model-platforms-and-bindings.md",
		"references/model-universal-platforms.md",
		"references/model-acceptance-runbook.md",
	}
	for _, name := range expected {
		if files[name] == nil {
			t.Fatalf("archive missing %q; files=%v", name, archiveFileNames(archive.File))
		}
	}
	skillFile, err := files["SKILL.md"].Open()
	if err != nil {
		t.Fatalf("open SKILL.md: %v", err)
	}
	defer skillFile.Close()
	skillContent, err := io.ReadAll(skillFile)
	if err != nil {
		t.Fatalf("read SKILL.md: %v", err)
	}
	if !strings.Contains(string(skillContent), "name: "+Name) {
		t.Fatalf("SKILL.md frontmatter has unexpected name")
	}
	billingFile, err := files["references/model-billing-configuration-and-estimation.md"].Open()
	if err != nil {
		t.Fatalf("open billing reference: %v", err)
	}
	defer billingFile.Close()
	billingContent, err := io.ReadAll(billingFile)
	if err != nil {
		t.Fatalf("read billing reference: %v", err)
	}
	for _, required := range []string{"/api/v1/pricing/estimate", "finalChargeAmount", "transactionType=task_billing"} {
		if !strings.Contains(string(billingContent), required) {
			t.Fatalf("billing reference missing %q", required)
		}
	}
}

func archiveFileNames(files []*zip.File) []string {
	names := make([]string, 0, len(files))
	for _, file := range files {
		names = append(names, file.Name)
	}
	return names
}
