package main

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

func TestTransformPlayworksHTMLNetworkRequirements(t *testing.T) {
	sourcePath := filepath.Join("..", "aiAssets", "DogCat3_Full.html")
	data, err := os.ReadFile(sourcePath)
	if err != nil {
		t.Fatalf("read source: %v", err)
	}

	tests := []struct {
		network     string
		wantMraid   int
		wantExitapi int
	}{
		{network: "al", wantMraid: 1},
		{network: "is", wantMraid: 1},
		{network: "gg", wantExitapi: 1},
		{network: "ap", wantExitapi: 1},
		{network: "fb"},
		{network: "mo"},
		{network: "vu"},
		{network: "mtg"},
	}

	for _, tt := range tests {
		t.Run(tt.network, func(t *testing.T) {
			html := transformPlayworksHTML(string(data), tt.network)
			assertCount(t, html, `src="mraid.js"`, tt.wantMraid)
			assertCount(t, html, `src="exitapi.js"`, tt.wantExitapi)
			assertCount(t, strings.ToLower(html), "</html>", 1)
			assertCount(t, strings.ToLower(html), "</head>", 1)

			for _, forbidden := range []string{
				`type="module"`,
				`crossorigin`,
				`console.error(`,
				`stats.min.js`,
				`insertYourRemoteDebuggingTokenHere`,
				`console.re/connector.js`,
			} {
				if strings.Contains(html, forbidden) {
					t.Fatalf("forbidden content remains: %s", forbidden)
				}
			}

			for _, required := range []string{"gameReady", "gameStart", "gameEnd", "gameClose"} {
				if !strings.Contains(html, required) {
					t.Fatalf("missing lifecycle symbol: %s", required)
				}
			}

			if tt.wantMraid == 1 {
				for _, required := range []string{"exposureChange", "viewableChange", "audioVolumeChange", "[MRAID error]", "stateChange"} {
					if !strings.Contains(html, required) {
						t.Fatalf("missing MRAID requirement marker: %s", required)
					}
				}
			}
		})
	}
}

func assertCount(t *testing.T, haystack, needle string, want int) {
	t.Helper()
	if got := strings.Count(haystack, needle); got != want {
		t.Fatalf("%q count = %d, want %d", needle, got, want)
	}
}
