package offsiteheal

import (
	"go/ast"
	"go/parser"
	"go/token"
	"testing"
)

// SCENARIO H — the reconciler is WIRED, asserted from main.go's source.
//
// Every test in this package passes on a reconciler that main.go never starts. That is this
// project's most-repeated failure shape: six features built and never wired, one of them an off-site
// restage event that existed and never fired once. The whole of R-204 item 4 is worth nothing if
// `Run` is not called.
//
// It walks the AST rather than grepping, because a commented-out call still contains the string, and
// it parses with comments DROPPED so a commented `go rec.Run(ctx)` cannot satisfy it.
//
// RED-PROOF: comment out the `go offsiteReconciler.Run(ctx)` line in cmd/hub/main.go → this fails.
func TestMainWiresTheOffsiteHealReconciler(t *testing.T) {
	const mainPath = "../../cmd/hub/main.go"
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, mainPath, nil, 0) // comments dropped on purpose
	if err != nil {
		t.Fatalf("parse %s: %v — the reconciler's wiring is now unasserted", mainPath, err)
	}

	var sawConstruct, sawRun bool
	ast.Inspect(f, func(n ast.Node) bool {
		call, ok := n.(*ast.CallExpr)
		if !ok {
			return true
		}
		sel, ok := call.Fun.(*ast.SelectorExpr)
		if !ok {
			return true
		}
		pkg, isIdent := sel.X.(*ast.Ident)
		// offsiteheal.NewReconciler(...)
		if isIdent && pkg.Name == "offsiteheal" && sel.Sel.Name == "NewReconciler" {
			sawConstruct = true
		}
		// <something>.Run(ctx) — the receiver is a local variable, so match on the method name and
		// confirm the construction separately. Narrow enough: this file has one Run per reconciler.
		if sel.Sel.Name == "Run" && isIdent && pkg.Name == "offsiteReconciler" {
			sawRun = true
		}
		return true
	})

	if !sawConstruct {
		t.Fatal("cmd/hub/main.go never calls offsiteheal.NewReconciler — R-204 item 4 ships inert")
	}
	if !sawRun {
		t.Fatal("the offsite self-heal reconciler is CONSTRUCTED but never Run — a stranded box would declare forever and nothing would answer")
	}
}
