package controlplane

import (
	"io/fs"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"testing"
)

func TestStoppedRuntimeFormulaStorageTransitionScopeHasOnlyOfflineCandidateOwningCallSites(t *testing.T) {
	const call = "offlinecandidateauthority.RunWithFormulaStorageTransitionScope("
	var callers []string
	err := filepath.WalkDir(".", func(path string, entry fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if entry.IsDir() {
			if path == ".git" || strings.HasPrefix(path, ".git"+string(filepath.Separator)) {
				return filepath.SkipDir
			}
			return nil
		}
		if filepath.Ext(path) != ".go" || strings.HasSuffix(path, "_test.go") {
			return nil
		}
		body, readErr := os.ReadFile(path)
		if readErr != nil {
			return readErr
		}
		if strings.Contains(string(body), call) {
			callers = append(callers, filepath.ToSlash(path))
		}
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
	wantCallers := []string{"offline_candidate.go"}
	if !reflect.DeepEqual(callers, wantCallers) {
		t.Fatalf("stopped-Runtime formula transition scope callers = %v, want %v", callers, wantCallers)
	}
	body, err := os.ReadFile("offline_candidate.go")
	if err != nil {
		t.Fatal(err)
	}
	helper := strings.Index(string(body), "func runOfflineCandidateFormulaStorageTransition(")
	materialize := strings.Index(string(body), "func prepareOfflineCandidateMaterializationsUnderApplyLock(")
	callAt := strings.Index(string(body), call)
	materializeCall := -1
	if materialize >= 0 {
		materializeCall = strings.Index(string(body)[materialize:], "runOfflineCandidateFormulaStorageTransition(")
	}
	if helper < 0 || callAt < helper || materialize < 0 || materializeCall < 0 {
		t.Fatalf("formula transition scope must be minted by the shared exact-candidate executor and used by materialization: helper=%d materialize=%d materializeCall=%d authorityCall=%d", helper, materialize, materializeCall, callAt)
	}
	orchestration, err := os.ReadFile("apply_all_source_revision_advance_orchestration.go")
	if err != nil {
		t.Fatal(err)
	}
	execute := strings.Index(string(orchestration), "func executeApplyAllSourceRevisionAdvanceAdmission(")
	if execute < 0 {
		t.Fatal("exact source-revision execution function is missing")
	}
	executeBody := string(orchestration)[execute:]
	callback := strings.Index(executeBody, "preflightAndExecuteSelected := func(")
	preflight := strings.Index(executeBody, "preflightApplyAllSourceRevisionAdvanceSelectedTarget(")
	revisionCall := strings.Index(executeBody, "runOfflineCandidateFormulaStorageTransition(")
	activation := strings.Index(executeBody, "prepareApplyAllSourceRevisionAdvanceActivation(")
	if callback < 0 || preflight < callback || revisionCall < preflight || activation < revisionCall {
		t.Fatalf("revision scope must wrap exact preflight through execution and end before final activation/verification: execute=%d callback=%d preflight=%d call=%d activation=%d", execute, callback, preflight, revisionCall, activation)
	}
}
