#!/usr/bin/env python3
"""Standalone OPI search reproduction; no network access or third-party Python deps.

Run: OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 TMPDIR="$PWD/.tmp" python3 -I solve.py OUTPUT.json
Requires a C++17 compiler (g++/libstdc++). On HPC, compile and run only inside a
compute allocation. Original source and fixed-trial source versions, scientific
run statistics, seed, exact replay count, and expected output hash are embedded.
The C++ search uses integer arithmetic and mt19937_64; std::shuffle is supplied
by libstdc++. Output hash verification catches any toolchain-dependent changes.
"""
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile

LICENSE_TEXT='MIT License\n\nCopyright (c) 2026 this workspace\'s authors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'
RECIPE={'method': 'prime-line', 'instance': 'p67-n32', 'seed': 1042, 'replay_count': 15117527, 'count_unit': 'affine lines', 'tail_argument': '100000', 'expected_score': 66, 'expected_artifact_sha256': '1824981228df5ad8328ece76227afe6e3483e5e476df9dc1e6ab6ebe01e8c7f3', 'original_cpp_sha256': '87d1e7021c7d384f30438da22d0e9a1c8a897a6ada5ba773e4667c8af2e6cf93', 'fixed_trial_cpp_sha256': 'e80b7081193ba1c1304903f7b8845ee349b67a9d612d5cc403011ab91c2f9656', 'original_run': {'seed': 1042, 'satisfied': 66, 'lines': 15117527, 'candidates': 1012874309, 'bases': 152, 'cpu_seconds': 9.9982, 'elapsed_seconds': 10.1414}, 'scientific_seconds_requested': 300.0, 'local_validation': {'status': 'accepted', 'score': {'satisfied': 66}, 'detail': {'field': 'prime', 'q': 67, 'n': 32, 'm': 66, 'degree': 31, 'satisfied': 66, 'signed_max_linsat': 66, 'check': 'Q (degree 31; n = 32 coefficients) evaluated exactly at all 66 nonzero points; 66 of the 66 values lie in their target sets'}}, 'incumbent_log_line': 'best=66 lines=15117527 candidates=1012874309 bases=152 elapsed_s=10.1414', 'compile_command': ['g++', '-std=c++17', '-O3', '-march=native', 'search.cpp', '-o', 'search'], 'source_provenance': 'Original implementation; Jordan et al. arXiv:2408.08292; Khattar et al. arXiv:2510.10967 (CC BY 4.0); MIT license for implementation. Official QArena instance data. No contestant artifact.'}
INSTANCE={'board': 'opi', 'instance': 'p67-n32', 'mode': 'ranked', 'cpu_seconds': 10, 'mem_mb': 128, 'field': 'prime', 'q': 67, 'n': 32, 'm': 66, 'r': 33, 'generator': 'SplitMix64 from seed (q << 32) | n, partial Fisher-Yates per point (SPEC_w2b_opi)', 'seed': 287762808864, 'convention': 'targets[i] is the target set of the evaluation point y = i + 1, a lowercase hexadecimal bitmask of fixed width ceil(q/4): bit v set means v is in F_y', 'targets': ['2fd0ea4deee402456', '5f18c2014bdda9ae3', '36512d70e4af40bcb', '601faa42de1495d7a', '204fc67d924a588fe', '45ae01f42067d617f', '23f628ded210a6dd8', '51732f0c3b257b413', '72834f52f74722664', '059638f3f72a3d481', '5ade5be8a324c302d', '20f9817707d2d1f68', '7dc8f21c71d069471', '0a630acf4cdcef823', '0464b2e9d28b5e99b', '74bca4e6963e3b404', '46dc688ed8e2697a8', '0fe2122e64433dbdc', '248f2ac3c4c055f7d', '36623f865dc89846e', '73f93068e2bca8aa8', '18274c2680f1fadcf', '133572cacb93e7890', '7239994855e619c2f', '08a0ac0e5ecf64fe3', '59a9c918f370cb287', '7d4b6976084671533', '60fa6456a0df1722d', '1686089331f55f3f1', '1d4497d002edf1e66', '5efdd6c28101e5ca4', '56c5dc3ede9105096', '03ba3aaef4bc70a05', '185cadfb09606ca7c', '605515d3a3ce91aea', '0ebcedae4c8440d7a', '649a5ce870cecb0ce', '046ea5553cdec896c', '30dd95087d52e6a0f', '2c63871e38be1483f', '4952e02276757f364', '3ad9ae217a5aa6c0c', '3b0e1d2fdbc288865', '0c49fb6da0cd8c7a2', '53ac3dc62ca252a7c', '07a85d3ded461d503', '432c78be45e1166d6', '1da4a7cb3f544a4c8', '3a750b2518e69fc70', '6c874654c6dde05aa', '70b6c69a65426970f', '54dd0fdf461014ad5', '3fe0bcc6b5148740e', '2ce73189e3042e2fd', '5092ae8ef17ca20fc', '31f528e7374ac181e', '311700df96765d98a', '3f8d6a180d9d681ce', '78be6b0c4a993aa4a', '366604af8f2e3d8d0', '1dc21b380ccad39b7', '539112766fcbe82e0', '5c6333826b0e47727', '495afe030ba8578e6', '505327a16ea9dabc2', '6d18e1b3c8576ec42']}
ORIGINAL_CPP='// Original implementation of interpolation (Prange) on an affine line.\n// Algorithm provenance: Jordan et al., arXiv:2408.08292, and Khattar et al.,\n// arXiv:2510.10967 Section III.1 (CC BY 4.0). No third-party code is copied.\n// MIT license for this implementation; see README.md.\n#include <algorithm>\n#include <chrono>\n#include <cstdint>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <vector>\nusing namespace std;\n\nstatic int mod(int64_t x,int q){x%=q;return x<0?x+q:x;}\nstatic int inv(int x,int q){int a=q,b=mod(x,q),u=0,v=1;while(b){int t=a/b;int r=a-t*b;a=b;b=r;r=u-t*v;u=v;v=r;}if(a!=1)throw runtime_error("nonunit");return mod(u,q);}\nstatic vector<int> multiply_root(const vector<int>& p,int x,int q){vector<int> z(p.size()+1);for(size_t i=0;i<p.size();++i){z[i]=mod(z[i]-(int64_t)x*p[i],q);z[i+1]=mod(z[i+1]+p[i],q);}return z;}\nstatic vector<int> polynomial(const vector<int>& roots,const vector<int>& vals,int t,int q){\n vector<int> b{1};for(int x:roots)b=multiply_root(b,x,q);\n vector<int> c(b.size());for(size_t k=0;k<c.size();++k)c[k]=mod((int64_t)t*b[k],q);\n for(size_t i=0;i<roots.size();++i){\n  int x=roots[i],d=1;for(size_t j=0;j<roots.size();++j)if(i!=j)d=mod((int64_t)d*(x-roots[j]),q);\n  int w=mod((int64_t)vals[i]*inv(d,q),q);vector<int> z(roots.size());z.back()=b.back();\n  for(int k=(int)z.size()-2;k>=0;--k)z[k]=mod(b[k+1]+(int64_t)x*z[k+1],q);\n  for(size_t k=0;k<z.size();++k)c[k]=mod(c[k]+(int64_t)w*z[k],q);\n }return c;\n}\n\nint main(int argc,char**argv){\n if(argc!=6){cerr<<"usage: prange_line TARGETS.txt SEED SECONDS OUTPUT.json LINES_PER_BASIS\\n";return 2;}\n ifstream f(argv[1]);int q,n;f>>q>>n;if(!f||q>257||n<2||n>=q-1)throw runtime_error("supported pilot: prime q<=257 and 2<=n<q-1");\n int m=q-1,k=n-1,W=(q+63)/64,L=0;while((1<<L)<=m)++L;\n vector<vector<int>> target(m);vector<vector<uint8_t>> hit(m,vector<uint8_t>(q));\n for(int j=0;j<m;++j){int r;f>>r;while(r--){int x;f>>x;target[j].push_back(x);hit[j][x]=1;}}if(!f)throw runtime_error("bad targets input");\n uint64_t seed=stoull(argv[2]),lines_per_basis=stoull(argv[5]),lines=0,candidates=0;double seconds=stod(argv[3]);mt19937_64 rng(seed);\n auto start=chrono::steady_clock::now();clock_t cpu_start=clock();int best=-1;vector<int> bestc;uint64_t bases=0;\n while(chrono::duration<double>(chrono::steady_clock::now()-start).count()<seconds){\n  vector<int> order(m);iota(order.begin(),order.end(),1);shuffle(order.begin(),order.end(),rng);\n  vector<int> roots(order.begin(),order.begin()+k),outside(order.begin()+k,order.end()),vals(k);\n  const int M=outside.size();vector<int> B(M,1),A(M,0),weight(k*M);\n  for(int j=0;j<M;++j)for(int x:roots)B[j]=mod((int64_t)B[j]*(outside[j]-x),q);\n  for(int i=0;i<k;++i){int d=1;for(int u=0;u<k;++u)if(i!=u)d=mod((int64_t)d*(roots[i]-roots[u]),q);int id=inv(d,q);vals[i]=target[roots[i]-1][rng()%target[roots[i]-1].size()];\n   for(int j=0;j<M;++j){int w=mod((int64_t)B[j]*inv(outside[j]-roots[i],q)*id,q);weight[i*M+j]=w;A[j]=mod(A[j]+(int64_t)vals[i]*w,q);}\n  }\n  vector<uint16_t> changes((size_t)k*q*M);\n  for(int i=0;i<k;++i)for(int d=0;d<q;++d)for(int j=0;j<M;++j)changes[((size_t)i*q+d)*M+j]=mod(d*weight[i*M+j],q);\n  vector<uint64_t> lookup((size_t)M*q*W,0);\n  for(int j=0;j<M;++j){int ib=inv(B[j],q);for(int a=0;a<q;++a)for(int v:target[outside[j]-1]){int t=mod((int64_t)(v-a)*ib,q);lookup[((size_t)j*q+a)*W+t/64]|=1ULL<<(t%64);}}\n  ++bases;vector<uint64_t> planes((size_t)L*W),eligible(W),trial(W);uint64_t lastmask=q%64?(1ULL<<(q%64))-1:~0ULL;\n  for(uint64_t step=0;step<lines_per_basis;++step){\n   if((step&4095)==0&&chrono::duration<double>(chrono::steady_clock::now()-start).count()>=seconds)break;\n   if(step){int i=rng()%k;const auto&tv=target[roots[i]-1];int nv=tv[rng()%tv.size()];int d=mod(nv-vals[i],q);vals[i]=nv;\n    const uint16_t* change=&changes[((size_t)i*q+d)*M];for(int j=0;j<M;++j){int a=A[j]+change[j];A[j]=a>=q?a-q:a;}\n   }\n   fill(planes.begin(),planes.end(),0);\n   for(int j=0;j<M;++j){const uint64_t* mask=&lookup[((size_t)j*q+A[j])*W];\n    for(int w=0;w<W;++w){uint64_t carry=mask[w];for(int b=0;carry&&b<L;++b){uint64_t prev=planes[b*W+w];planes[b*W+w]=prev^carry;carry&=prev;}}\n   }\n   fill(eligible.begin(),eligible.end(),~0ULL);eligible.back()=lastmask;int value=0;\n   for(int b=L-1;b>=0;--b){uint64_t any=0;for(int w=0;w<W;++w){trial[w]=eligible[w]&planes[b*W+w];any|=trial[w];}if(any){value|=1<<b;eligible=trial;}}\n   ++lines;candidates+=q;\n   if(value+k>best){int t=-1;for(int w=0;w<W&&t<0;++w)if(eligible[w])t=w*64+__builtin_ctzll(eligible[w]);\n    auto c=polynomial(roots,vals,t,q);int score=0;for(int y=1;y<q;++y){int z=0;for(int i=n-1;i>=0;--i)z=mod((int64_t)z*y+c[i],q);score+=hit[y-1][z];}\n    if(score!=value+k)throw runtime_error("independent Horner score mismatch");best=score;bestc=c;ofstream out(argv[4]);out<<"{\\"coeffs\\":[";for(int i=0;i<n;++i)out<<(i?",":"")<<c[i];out<<"]}\\n";out.close();\n    cerr<<"best="<<best<<" lines="<<lines<<" candidates="<<candidates<<" bases="<<bases<<" elapsed_s="<<chrono::duration<double>(chrono::steady_clock::now()-start).count()<<"\\n";\n   }\n   if(best==m)break;\n  }\n  if(best==m)break;\n }\n cout<<"{\\"seed\\":"<<seed<<",\\"satisfied\\":"<<best<<",\\"lines\\":"<<lines<<",\\"candidates\\":"<<candidates<<",\\"bases\\":"<<bases<<",\\"cpu_seconds\\":"<<double(clock()-cpu_start)/CLOCKS_PER_SEC<<",\\"elapsed_seconds\\":"<<chrono::duration<double>(chrono::steady_clock::now()-start).count()<<"}\\n";\n}\n'
FIXED_TRIAL_CPP='// Original implementation of interpolation (Prange) on an affine line.\n// Algorithm provenance: Jordan et al., arXiv:2408.08292, and Khattar et al.,\n// arXiv:2510.10967 Section III.1 (CC BY 4.0). No third-party code is copied.\n// MIT license for this implementation; see README.md.\n#include <algorithm>\n#include <chrono>\n#include <cstdint>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <vector>\nusing namespace std;\n\nstatic int mod(int64_t x,int q){x%=q;return x<0?x+q:x;}\nstatic int inv(int x,int q){int a=q,b=mod(x,q),u=0,v=1;while(b){int t=a/b;int r=a-t*b;a=b;b=r;r=u-t*v;u=v;v=r;}if(a!=1)throw runtime_error("nonunit");return mod(u,q);}\nstatic vector<int> multiply_root(const vector<int>& p,int x,int q){vector<int> z(p.size()+1);for(size_t i=0;i<p.size();++i){z[i]=mod(z[i]-(int64_t)x*p[i],q);z[i+1]=mod(z[i+1]+p[i],q);}return z;}\nstatic vector<int> polynomial(const vector<int>& roots,const vector<int>& vals,int t,int q){\n vector<int> b{1};for(int x:roots)b=multiply_root(b,x,q);\n vector<int> c(b.size());for(size_t k=0;k<c.size();++k)c[k]=mod((int64_t)t*b[k],q);\n for(size_t i=0;i<roots.size();++i){\n  int x=roots[i],d=1;for(size_t j=0;j<roots.size();++j)if(i!=j)d=mod((int64_t)d*(x-roots[j]),q);\n  int w=mod((int64_t)vals[i]*inv(d,q),q);vector<int> z(roots.size());z.back()=b.back();\n  for(int k=(int)z.size()-2;k>=0;--k)z[k]=mod(b[k+1]+(int64_t)x*z[k+1],q);\n  for(size_t k=0;k<z.size();++k)c[k]=mod(c[k]+(int64_t)w*z[k],q);\n }return c;\n}\n\nint main(int argc,char**argv){\n if(argc!=6){cerr<<"usage: prange_line TARGETS.txt SEED SECONDS OUTPUT.json LINES_PER_BASIS\\n";return 2;}\n ifstream f(argv[1]);int q,n;f>>q>>n;if(!f||q>257||n<2||n>=q-1)throw runtime_error("supported pilot: prime q<=257 and 2<=n<q-1");\n int m=q-1,k=n-1,W=(q+63)/64,L=0;while((1<<L)<=m)++L;\n vector<vector<int>> target(m);vector<vector<uint8_t>> hit(m,vector<uint8_t>(q));\n for(int j=0;j<m;++j){int r;f>>r;while(r--){int x;f>>x;target[j].push_back(x);hit[j][x]=1;}}if(!f)throw runtime_error("bad targets input");\n uint64_t seed=stoull(argv[2]),lines_per_basis=stoull(argv[5]),lines=0,candidates=0;uint64_t replay_limit=stoull(argv[3]);mt19937_64 rng(seed);\n auto start=chrono::steady_clock::now();clock_t cpu_start=clock();int best=-1;vector<int> bestc;uint64_t bases=0;\n while(lines<replay_limit){\n  vector<int> order(m);iota(order.begin(),order.end(),1);shuffle(order.begin(),order.end(),rng);\n  vector<int> roots(order.begin(),order.begin()+k),outside(order.begin()+k,order.end()),vals(k);\n  const int M=outside.size();vector<int> B(M,1),A(M,0),weight(k*M);\n  for(int j=0;j<M;++j)for(int x:roots)B[j]=mod((int64_t)B[j]*(outside[j]-x),q);\n  for(int i=0;i<k;++i){int d=1;for(int u=0;u<k;++u)if(i!=u)d=mod((int64_t)d*(roots[i]-roots[u]),q);int id=inv(d,q);vals[i]=target[roots[i]-1][rng()%target[roots[i]-1].size()];\n   for(int j=0;j<M;++j){int w=mod((int64_t)B[j]*inv(outside[j]-roots[i],q)*id,q);weight[i*M+j]=w;A[j]=mod(A[j]+(int64_t)vals[i]*w,q);}\n  }\n  vector<uint16_t> changes((size_t)k*q*M);\n  for(int i=0;i<k;++i)for(int d=0;d<q;++d)for(int j=0;j<M;++j)changes[((size_t)i*q+d)*M+j]=mod(d*weight[i*M+j],q);\n  vector<uint64_t> lookup((size_t)M*q*W,0);\n  for(int j=0;j<M;++j){int ib=inv(B[j],q);for(int a=0;a<q;++a)for(int v:target[outside[j]-1]){int t=mod((int64_t)(v-a)*ib,q);lookup[((size_t)j*q+a)*W+t/64]|=1ULL<<(t%64);}}\n  ++bases;vector<uint64_t> planes((size_t)L*W),eligible(W),trial(W);uint64_t lastmask=q%64?(1ULL<<(q%64))-1:~0ULL;\n  for(uint64_t step=0;step<lines_per_basis;++step){\n   if(lines>=replay_limit)break;\n   if(step){int i=rng()%k;const auto&tv=target[roots[i]-1];int nv=tv[rng()%tv.size()];int d=mod(nv-vals[i],q);vals[i]=nv;\n    const uint16_t* change=&changes[((size_t)i*q+d)*M];for(int j=0;j<M;++j){int a=A[j]+change[j];A[j]=a>=q?a-q:a;}\n   }\n   fill(planes.begin(),planes.end(),0);\n   for(int j=0;j<M;++j){const uint64_t* mask=&lookup[((size_t)j*q+A[j])*W];\n    for(int w=0;w<W;++w){uint64_t carry=mask[w];for(int b=0;carry&&b<L;++b){uint64_t prev=planes[b*W+w];planes[b*W+w]=prev^carry;carry&=prev;}}\n   }\n   fill(eligible.begin(),eligible.end(),~0ULL);eligible.back()=lastmask;int value=0;\n   for(int b=L-1;b>=0;--b){uint64_t any=0;for(int w=0;w<W;++w){trial[w]=eligible[w]&planes[b*W+w];any|=trial[w];}if(any){value|=1<<b;eligible=trial;}}\n   ++lines;candidates+=q;\n   if(value+k>best){int t=-1;for(int w=0;w<W&&t<0;++w)if(eligible[w])t=w*64+__builtin_ctzll(eligible[w]);\n    auto c=polynomial(roots,vals,t,q);int score=0;for(int y=1;y<q;++y){int z=0;for(int i=n-1;i>=0;--i)z=mod((int64_t)z*y+c[i],q);score+=hit[y-1][z];}\n    if(score!=value+k)throw runtime_error("independent Horner score mismatch");best=score;bestc=c;ofstream out(argv[4]);out<<"{\\"coeffs\\":[";for(int i=0;i<n;++i)out<<(i?",":"")<<c[i];out<<"]}\\n";out.close();\n    cerr<<"best="<<best<<" lines="<<lines<<" candidates="<<candidates<<" bases="<<bases<<" elapsed_s="<<chrono::duration<double>(chrono::steady_clock::now()-start).count()<<"\\n";\n   }\n   if(best==m)break;\n  }\n  if(best==m)break;\n }\n cout<<"{\\"seed\\":"<<seed<<",\\"satisfied\\":"<<best<<",\\"lines\\":"<<lines<<",\\"candidates\\":"<<candidates<<",\\"bases\\":"<<bases<<",\\"cpu_seconds\\":"<<double(clock()-cpu_start)/CLOCKS_PER_SEC<<",\\"elapsed_seconds\\":"<<chrono::duration<double>(chrono::steady_clock::now()-start).count()<<"}\\n";\n}\n'

def main():
    if len(sys.argv)>1 and sys.argv[1]=='--metadata':
        print(json.dumps(RECIPE,indent=2))
        return
    output=Path(sys.argv[1] if len(sys.argv)>1 else 'candidate.json').resolve()
    output.parent.mkdir(parents=True,exist_ok=True)
    tmp_root=Path(os.environ.get('TMPDIR',str(Path.cwd()/'.opi_replay_tmp')))
    tmp_root.mkdir(parents=True,exist_ok=True)
    for name in ['OPENBLAS_NUM_THREADS','OMP_NUM_THREADS','MKL_NUM_THREADS']:
        os.environ[name]='1'
    with tempfile.TemporaryDirectory(prefix='opi-replay-',dir=tmp_root) as tmp:
        work=Path(tmp)
        (work/'search.cpp').write_text(FIXED_TRIAL_CPP)
        table=work/'targets.txt'
        with table.open('w') as f:
            if INSTANCE['field']=='prime':
                f.write(f"{INSTANCE['q']} {INSTANCE['n']}\n")
                for mask in INSTANCE['targets']:
                    bits=int(mask,16)
                    values=[v for v in range(INSTANCE['q']) if bits>>v&1]
                    f.write(str(len(values))+' '+' '.join(map(str,values))+'\n')
            else:
                f.write(f"{INSTANCE['b']} {INSTANCE['n']} {INSTANCE['modulus']}\n")
                for rows in INSTANCE['matrices']:
                    f.write(' '.join(map(str,rows))+'\n')
        compiler=shutil.which('g++')
        if not compiler:
            raise RuntimeError('g++ with C++17 support is required')
        subprocess.run([compiler,'-std=c++17','-O3','-march=native',str(work/'search.cpp'),'-o',str(work/'search')],check=True)
        print(json.dumps({'recipe':RECIPE,'compiler':subprocess.check_output([compiler,'--version'],text=True).splitlines()[0]}),flush=True)
        subprocess.run([str(work/'search'),str(table),str(RECIPE['seed']),str(RECIPE['replay_count']),str(output),RECIPE['tail_argument']],check=True)
    observed=hashlib.sha256(output.read_bytes()).hexdigest()
    if observed!=RECIPE['expected_artifact_sha256']:
        raise RuntimeError(f"Replay hash differs: expected {RECIPE['expected_artifact_sha256']}, got {observed}. Check libstdc++ std::shuffle/compiler version.")
    print(json.dumps({'output':str(output),'sha256':observed,'reproduced':True}))

if __name__=='__main__':
    main()
