// Package engine runs a deliberately small dependency experiment, not a load benchmark.
package engine

import (
 "context"
 "errors"
 "fmt"
 "sync"
 "time"
)

var ErrUnavailable=errors.New("temporary dependency failure")
type Config struct {Preset string `json:"preset"`; Variant string `json:"variant"`}
type Caller func(context.Context,int,int) error
type Table struct {Title string `json:"title"`;Columns []string `json:"columns"`;Rows [][]any `json:"rows"`}
type Result struct {Title string `json:"title"`;Summary string `json:"summary"`;Metrics [][2]any `json:"metrics"`;Trace []string `json:"trace"`;Tables []Table `json:"tables"`}
type breaker struct {mu sync.Mutex;failures int;until time.Time;probe bool}
func(b *breaker)allow()bool{b.mu.Lock();defer b.mu.Unlock();if b.failures<2{return true};if time.Now().Before(b.until)||b.probe{return false};b.probe=true;return true}
func(b *breaker)finish(err error){b.mu.Lock();defer b.mu.Unlock();b.probe=false;if err==nil{b.failures=0;return};b.failures++;if b.failures>=2{b.until=time.Now().Add(90*time.Millisecond)}}
func pause(ctx context.Context,d time.Duration)error{t:=time.NewTimer(d);defer t.Stop();select{case<-ctx.Done():return ctx.Err();case<-t.C:return nil}}
func Fixture(preset string)Caller{return func(ctx context.Context,id,attempt int)error{
 d:=12*time.Millisecond;if preset=="slow"||preset=="overload"{d=100*time.Millisecond};if err:=pause(ctx,d);err!=nil{return err};if preset=="recovery"&&id<4{return ErrUnavailable};return nil
}}
func Run(ctx context.Context,c Config)(Result,error){return Execute(ctx,c,Fixture(c.Preset))}
func Execute(parent context.Context,c Config,call Caller)(Result,error){
 if c.Preset!="slow"&&c.Preset!="overload"&&c.Preset!="recovery"{return Result{},errors.New("choose a listed resilience scenario")}
 if c.Variant!="safe"&&c.Variant!="broken"{return Result{},errors.New("invalid implementation")}
 ctx,cancel:=context.WithTimeout(parent,3*time.Second);defer cancel();safe:=c.Variant=="safe";start:=time.Now()
 var mu sync.Mutex;active,peak,calls,success,failed,shed,opened:=0,0,0,0,0,0,0
 rows:=[][]any{};slots:=make(chan struct{},3);br:=&breaker{};var wg sync.WaitGroup
 event:=func(id int,note string){mu.Lock();defer mu.Unlock();if len(rows)<72{rows=append(rows,[]any{time.Since(start).Milliseconds(),id,note})}}
 request:=func(id int){defer wg.Done()
  if safe{select{case slots<-struct{}{}:defer func(){<-slots}();default:mu.Lock();shed++;mu.Unlock();event(id,"bulkhead full: rejected before starting dependency work");return}}
  budget:=ctx;var finish context.CancelFunc
  if safe{budget,finish=context.WithTimeout(ctx,85*time.Millisecond);defer finish()}
  attempts:=3;if safe{attempts=2};var last error
  for a:=0;a<attempts;a++{
   if budget.Err()!=nil{last=budget.Err();break}
   if safe&&!br.allow(){mu.Lock();opened++;mu.Unlock();last=ErrUnavailable;event(id,"circuit open: dependency call skipped");break}
   attemptCtx:=budget;var stop context.CancelFunc
   if safe{attemptCtx,stop=context.WithTimeout(budget,35*time.Millisecond)}
   mu.Lock();calls++;active++;if active>peak{peak=active};mu.Unlock();event(id,fmt.Sprintf("attempt %d started",a+1))
   last=call(attemptCtx,id,a);if stop!=nil{stop()}
   mu.Lock();active--;mu.Unlock();if safe{br.finish(last)}
   if last==nil{break};event(id,"attempt ended: "+last.Error())
   if !errors.Is(last,ErrUnavailable)&&!errors.Is(last,context.DeadlineExceeded){break}
   if a+1<attempts&&safe{if err:=pause(budget,time.Duration(5+(id*7+a*3)%13)*time.Millisecond);err!=nil{last=err;break}}
  }
  mu.Lock();if last==nil{success++}else{failed++};mu.Unlock()
 }
 n:=12;if c.Preset=="slow"{n=6};if c.Preset=="recovery"{n=8}
 for i:=0;i<n;i++{wg.Add(1);if c.Preset=="recovery"{request(i);if err:=pause(ctx,50*time.Millisecond);err!=nil{break}}else{go request(i)}}
 wg.Wait()
 trace:=[]string{"Each dependency attempt waits on a real timer and honors cancellation. The browser transport is an in-process fixture; the native adapter uses loopback HTTP.","Without safeguards: every request may call the dependency immediately and retry up to three times.","With safeguards: three in-flight requests, an 85 ms request budget, 35 ms attempts, two attempts at most, and deterministic bounded jitter.","The circuit opens after two failed attempts, waits 90 ms, then permits one recovery probe. This is a teaching policy, not a universal production threshold.","All started goroutines are joined before returning. Rejected requests are visible failures; limits protect capacity rather than inventing successful work."}
 title:="Unbounded callers share the failure";if safe{title="Bound the work and expose the recovery decision"}
 return Result{Title:title,Summary:"Actual Go executes this experiment. Timer durations and scheduling vary; these tiny fixtures do not establish production throughput.",Metrics:[][2]any{{"Dependency attempts",calls},{"Peak in flight",peak},{"Succeeded",success},{"Failed",failed},{"Shed before work",shed},{"Circuit skips",opened},{"Active at finish",active}},Trace:trace,Tables:[]Table{{Title:"Attempt timeline",Columns:[]string{"Elapsed ms","Request","Decision"},Rows:rows}}},nil
}
