package main

import (
	"archive/zip"
	"io"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestDogCat3MraidChecker(t *testing.T) {
	root := filepath.Join("..", "aiAssets", "DogCat3")
	files, err := collectDogCat3MraidTargets(root)
	if err != nil {
		t.Fatalf("collect targets: %v", err)
	}
	if len(files) == 0 {
		t.Fatalf("no DogCat3 MRAID targets found")
	}

	for _, file := range files {
		t.Run(filepath.Base(file), func(t *testing.T) {
			html, displayPath, err := readDogCat3HTML(file)
			if err != nil {
				t.Fatalf("read target: %v", err)
			}
			issues := checkMraid(html, displayPath)
			if len(issues) == 0 {
				return
			}
			var parts []string
			for _, issue := range issues {
				parts = append(parts, issue.ID+": "+issue.Title+" ("+issue.Severity+")")
			}
			t.Fatalf("MRAID checker issues:\n%s", strings.Join(parts, "\n"))
		})
	}
}

func collectDogCat3MraidTargets(root string) ([]string, error) {
	var out []string
	for _, folder := range []string{"Applovin", "Ironsource", "Unity"} {
		dir := filepath.Join(root, folder)
		entries, err := os.ReadDir(dir)
		if err != nil {
			if os.IsNotExist(err) {
				continue
			}
			return nil, err
		}
		for _, entry := range entries {
			if entry.IsDir() {
				continue
			}
			name := strings.ToLower(entry.Name())
			if strings.HasSuffix(name, ".html") || strings.HasSuffix(name, ".htm") || strings.HasSuffix(name, ".zip") {
				out = append(out, filepath.Join(dir, entry.Name()))
			}
		}
	}
	return out, nil
}

func readDogCat3HTML(file string) (html string, displayPath string, err error) {
	if strings.HasSuffix(strings.ToLower(file), ".zip") {
		zr, err := zip.OpenReader(file)
		if err != nil {
			return "", "", err
		}
		defer zr.Close()
		for _, entry := range zr.File {
			if strings.EqualFold(entry.Name, "index.html") {
				rc, err := entry.Open()
				if err != nil {
					return "", "", err
				}
				defer rc.Close()
				data, err := io.ReadAll(rc)
				if err != nil {
					return "", "", err
				}
				return string(data), file + "#index.html", nil
			}
		}
		return "", "", os.ErrNotExist
	}
	data, err := os.ReadFile(file)
	if err != nil {
		return "", "", err
	}
	return string(data), file, nil
}
