package main
import ("context";"encoding/json";"errors";"fmt";"io";"net/http";"sort";"strconv";"strings";"sync";"sync/atomic";"time")

var ErrTiming=errors.New("invalid elapsed time")
func ElapsedMS(start,end time.Time)(int64,error){
 if end.Before(start){return 0,ErrTiming}
 return end.Sub(start).Milliseconds(),nil
}

var ErrRequestID=errors.New("invalid server request id")
type requestKey struct{}
func validRequestID(id string)bool{
 if len(id)<1||len(id)>64{return false}
 for _,b:=range []byte(id){if !(b>='a'&&b<='z'||b>='A'&&b<='Z'||b>='0'&&b<='9'||b=='.'||b=='_'||b=='-'){return false}}
 return true
}
func WithRequestID(ctx context.Context,id string)(context.Context,error){
 if ctx==nil||!validRequestID(id){return nil,ErrRequestID}
 return context.WithValue(ctx,requestKey{},id),nil
}
func RequestID(ctx context.Context)(string,bool){
 if ctx==nil{return "",false}
 id,ok:=ctx.Value(requestKey{}).(string);return id,ok
}

var ErrLabels=errors.New("invalid bounded labels")
func BoundedMethod(raw string)string{
 switch raw{case "GET","HEAD","POST","DELETE":return raw;default:return "OTHER"}
}
func BoundedRoute(path string)string{
 switch path{case "/healthz","/notes":return path}
 if strings.HasPrefix(path,"/notes/"){
  raw:=strings.TrimPrefix(path,"/notes/");id,err:=strconv.Atoi(raw)
  if err==nil&&id>=1&&id<=1000000&&strconv.Itoa(id)==raw{return "/notes/:id"}
 }
 return "unmatched"
}
func knownMethod(method string)bool{return method=="GET"||method=="HEAD"||method=="POST"||method=="DELETE"||method=="OTHER"}
func knownRoute(route string)bool{return route=="/healthz"||route=="/notes"||route=="/notes/:id"||route=="unmatched"}
func statusClass(status int)string{
 if status==0{return "none"};if status<200||status>599{return "invalid"}
 return strconv.Itoa(status/100)+"xx"
}
func validOutcome(status int,outcome string)bool{
 if statusClass(status)=="invalid"{return false}
 if status==0{return outcome=="panic"}
 return outcome=="completed"||outcome=="write_error"||outcome=="panic"
}

var ErrEvent=errors.New("invalid request event")
type Event struct{
 RequestID string `json:"request_id"`
 Method string `json:"method"`
 Route string `json:"route"`
 Status int `json:"status"`
 DurationMS *int64 `json:"duration_ms"`
 Outcome string `json:"outcome"`
 Sensitive map[string]string `json:"sensitive,omitempty"`
}
type logEntry struct{
 RequestID string `json:"request_id"`
 Method string `json:"method"`
 Route string `json:"route"`
 Status int `json:"status"`
 DurationMS *int64 `json:"duration_ms"`
 Outcome string `json:"outcome"`
}
func encodeLog(entry logEntry)([]byte,error){return json.Marshal(entry)}
func MarshalEvent(event Event)([]byte,error){
 if !validRequestID(event.RequestID)||!knownMethod(event.Method)||!knownRoute(event.Route)||!validOutcome(event.Status,event.Outcome){return nil,ErrEvent}
 if event.DurationMS!=nil&&*event.DurationMS<0{return nil,ErrEvent}
 // Copy only approved fields; Sensitive is intentionally never serialized.
 return encodeLog(logEntry{event.RequestID,event.Method,event.Route,event.Status,event.DurationMS,event.Outcome})
}

var ErrCounter=errors.New("counter overflow")
type counterKey struct{Method,Route,Class string}
type CounterRow struct{
 Method string `json:"method"`;Route string `json:"route"`;Class string `json:"class"`
 Requests uint64 `json:"requests"`;ServerErrors uint64 `json:"server_errors"`
 Aborted uint64 `json:"aborted"`;WriteErrors uint64 `json:"write_errors"`
}
type CounterStore struct{mu sync.Mutex;rows map[counterKey]CounterRow}
func NewCounterStore()*CounterStore{return &CounterStore{rows:make(map[counterKey]CounterRow)}}
func(s *CounterStore)Record(method,route string,status int,outcome string)error{
 if !knownMethod(method)||!knownRoute(route)||!validOutcome(status,outcome){return ErrLabels}
 s.mu.Lock();defer s.mu.Unlock()
 key:=counterKey{method,route,statusClass(status)};row:=s.rows[key]
 row.Method,row.Route,row.Class=key.Method,key.Route,key.Class
 if row.Requests==^uint64(0){return ErrCounter}
 row.Requests++
 if status>=500{row.ServerErrors++}
 if outcome=="panic"{row.Aborted++}
 if outcome=="write_error"{row.WriteErrors++}
 s.rows[key]=row;return nil
}
func(s *CounterStore)Snapshot()[]CounterRow{
 s.mu.Lock();defer s.mu.Unlock();result:=make([]CounterRow,0,len(s.rows))
 for _,row:=range s.rows{result=append(result,row)}
 sort.Slice(result,func(i,j int)bool{a,b:=result[i],result[j];if a.Route!=b.Route{return a.Route<b.Route};if a.Method!=b.Method{return a.Method<b.Method};return a.Class<b.Class})
 return result
}

var ErrHistogram=errors.New("invalid histogram observation")
var bucketBoundsMS=[6]int64{10,50,100,500,1000,5000}
type Histogram struct{
 Count uint64 `json:"count"`
 SumMS uint64 `json:"sum_ms"`
 Buckets [7]uint64 `json:"cumulative_buckets"`
}
type PercentileBound struct{State string `json:"state"`;UpperMS *int64 `json:"upper_ms"`}
func(h *Histogram)Observe(ms int64)error{
 if ms<0||h.Count==^uint64(0)||uint64(ms)>^uint64(0)-h.SumMS{return ErrHistogram}
 h.Count++;h.SumMS+=uint64(ms)
 for i,bound:=range bucketBoundsMS{if ms<=bound{h.Buckets[i]++}}
 h.Buckets[len(bucketBoundsMS)]++
 return nil
}
func(h Histogram)MeanMS()*float64{
 if h.Count==0{return nil};value:=float64(h.SumMS)/float64(h.Count);return &value
}
func(h Histogram)P95Bound()PercentileBound{
 if h.Count==0{return PercentileBound{State:"empty"}}
 // ceil(0.95*n) = n-floor(n/20), avoiding multiplication overflow.
 rank:=h.Count-h.Count/20
 for i,bound:=range bucketBoundsMS{if h.Buckets[i]>=rank{value:=bound;return PercentileBound{State:"bounded",UpperMS:&value}}}
 return PercentileBound{State:"unbounded"}
}
type histogramKey struct{Method,Route string}
type HistogramRow struct{Method string `json:"method"`;Route string `json:"route"`;Histogram Histogram `json:"histogram"`}
type HistogramStore struct{mu sync.Mutex;rows map[histogramKey]Histogram}
func NewHistogramStore()*HistogramStore{return &HistogramStore{rows:make(map[histogramKey]Histogram)}}
func(s *HistogramStore)Observe(method,route string,ms int64)error{
 if !knownMethod(method)||!knownRoute(route){return ErrLabels}
 s.mu.Lock();defer s.mu.Unlock();key:=histogramKey{method,route};histogram:=s.rows[key]
 if err:=histogram.Observe(ms);err!=nil{return err};s.rows[key]=histogram;return nil
}
func(s *HistogramStore)Snapshot()[]HistogramRow{
 s.mu.Lock();defer s.mu.Unlock();rows:=make([]HistogramRow,0,len(s.rows));for key,h:=range s.rows{rows=append(rows,HistogramRow{key.Method,key.Route,h})}
 sort.Slice(rows,func(i,j int)bool{a,b:=rows[i],rows[j];if a.Route!=b.Route{return a.Route<b.Route};return a.Method<b.Method});return rows
}

var ErrInstrumentation=errors.New("explicit instrumentation dependencies required")
type Sink interface{Log(Event)error}
type WriterSink struct{mu sync.Mutex;Writer io.Writer}
func(s *WriterSink)Log(event Event)error{
 data,err:=MarshalEvent(event);if err!=nil{return err};data=append(data,'\n')
 s.mu.Lock();defer s.mu.Unlock();n,err:=s.Writer.Write(data);if err==nil&&n!=len(data){return io.ErrShortWrite};return err
}
type captureWriter struct{http.ResponseWriter;status int;writeFailed bool}
func(w *captureWriter)WriteHeader(status int){
 if w.status!=0{return}
 if status>=100&&status<200{w.ResponseWriter.WriteHeader(status);return}
 w.ResponseWriter.WriteHeader(status);w.status=status
}
func(w *captureWriter)Write(data []byte)(int,error){
 if w.status==0{w.WriteHeader(200)};n,err:=w.ResponseWriter.Write(data);if err==nil&&n!=len(data){err=io.ErrShortWrite};if err!=nil{w.writeFailed=true};return n,err
}
func fallbackID(counter *atomic.Uint64)string{return fmt.Sprintf("fallback-%d",counter.Add(1))}
// Ordinary JSON handlers only: this wrapper does not promise optional
// streaming/hijacking interface transparency or distributed trace propagation.
func Instrument(next http.Handler,clock func()time.Time,newID func()string,sink Sink,counters *CounterStore,histograms *HistogramStore,onError func(error))(http.Handler,error){
    panic("implement the stated contract")
}
