// Session 98: public score mask; Session 89 search and transitions preserved.
// The fit mode and fixed-key path decoder preserve Session 88 behavior.
// Compile: g++ -O3 -std=c++17 recovery_benchmark_engine.cpp -o recovery_engine
#include <algorithm>
#include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <random>
#include <stdexcept>
#include <string>
#include <vector>

constexpr int A=30, F=29, B=29;
constexpr double NEG=-1e290;

struct Path {
    double score=NEG;
    int end=0;
    std::vector<int> plain, skips;
};

struct Decoder {
    int period;
    bool selective;
    const std::vector<double>& logp;
    long long evaluations=0;
    double ll(int a,int b,int c) const {return logp[(a*A+b)*A+c];}
    int sid(int phase,int a,int b) const {return (phase*A+a)*A+b;}

    Path run(const std::vector<int>& cipher,const std::vector<int>& start,
             const std::vector<int>& finish,const std::vector<int>& mask,const std::vector<int>& key,
             int phase0,bool trace) {
        ++evaluations;
        const int n=cipher.size(), states=period*A*A;
        Path answer;
        if (!selective) {
            int phase=phase0,a=B,b=B;
            answer.score=0;
            for(int i=0;i<n;++i) {
                if(start[i]) a=b=B;
                int p=(cipher[i]-key[phase]+F)%F;
                if(mask[i]) answer.score+=ll(a,b,p);
                if(mask[i] && finish[i]) answer.score+=ll(b,p,B);
                if(trace) answer.plain.push_back(p);
                a=b;b=p;phase=(phase+1)%period;
            }
            answer.end=phase;return answer;
        }
        std::vector<double> current(states,NEG),next(states,NEG);
        std::vector<int> active{sid(phase0,B,B)},nextActive;
        current[active[0]]=0;
        std::vector<int> parents;
        std::vector<unsigned char> actions;
        if(trace) {parents.assign((size_t)n*states,-1);actions.resize((size_t)n*states);}
        const double fPenalty=std::log(.5);
        for(int i=0;i<n;++i) {
            for(int state:nextActive) next[state]=NEG;
            nextActive.clear();
            auto add=[&](int state,double score,int parent,bool skip) {
                if(next[state]==NEG) nextActive.push_back(state);
                if(score>next[state]+1e-12) {
                    next[state]=score;
                    if(trace) {parents[(size_t)i*states+state]=parent;actions[(size_t)i*states+state]=skip;}
                }
            };
            for(int state:active) {
                int phase=state/(A*A),a=(state/A)%A,b=state%A;
                if(start[i]) a=b=B;
                int p=(cipher[i]-key[phase]+F)%F;
                double normal=current[state]+(mask[i]?(ll(a,b,p)+(p==0?fPenalty:0)):0);
                if(mask[i] && finish[i]) normal+=ll(b,p,B);
                add(sid((phase+1)%period,finish[i]?B:b,finish[i]?B:p),normal,state,false);
                if(cipher[i]==0) {
                    double skipped=current[state]+(mask[i]?(ll(a,b,0)+fPenalty):0);
                    if(mask[i] && finish[i]) skipped+=ll(b,0,B);
                    add(sid(phase,finish[i]?B:b,finish[i]?B:0),skipped,state,true);
                }
            }
            current.swap(next);active.swap(nextActive);
        }
        int best=-1;
        for(int state:active)
            if(best<0 || current[state]>current[best]+1e-12 ||
               (std::abs(current[state]-current[best])<=1e-12 && state<best)) best=state;
        if(best<0) throw std::runtime_error("No legal path");
        answer.score=current[best];answer.end=best/(A*A);
        if(trace) {
            answer.plain.resize(n);
            for(int i=n-1;i>=0;--i) {
                int parent=parents[(size_t)i*states+best];
                if(parent<0) throw std::runtime_error("Missing traceback parent");
                bool skip=actions[(size_t)i*states+best];
                answer.plain[i]=skip?0:(cipher[i]-key[parent/(A*A)]+F)%F;
                if(skip) answer.skips.push_back(i);
                best=parent;
            }
            std::reverse(answer.skips.begin(),answer.skips.end());
        }
        return answer;
    }
};

template<class T> void array_json(const std::vector<T>& a) {
    std::cout<<'[';
    for(size_t i=0;i<a.size();++i) {if(i)std::cout<<',';std::cout<<a[i];}
    std::cout<<']';
}
void path_json(const Path& p) {
    std::cout<<"{\"score\":"<<p.score<<",\"end_phase\":"<<p.end<<",\"plaintext\":";
    array_json(p.plain);std::cout<<",\"skips\":";array_json(p.skips);std::cout<<'}';
}

// All shifts are scored from the same base array, including the identity.
// Strict improvement preserves the original array on a score tie.
int rotate_key(Decoder& decoder, const std::vector<int>& c,
               const std::vector<int>& s, const std::vector<int>& e, const std::vector<int>& m,
               std::vector<int>& key, int phase, double& current,
               std::vector<double>& scores) {
    const std::vector<int> base=key;
    int choice=0;
    double top=current;
    scores.clear();
    for(int shift=0;shift<decoder.period;++shift) {
        std::vector<int> proposal=base;
        std::rotate(proposal.begin(),proposal.begin()+shift,proposal.end());
        double score=decoder.run(c,s,e,m,proposal,phase,false).score;
        scores.push_back(score);
        if(score>top+1e-10){top=score;choice=shift;}
    }
    std::rotate(key.begin(),key.begin()+choice,key.end());
    current=top;
    return choice;
}

int main() {
    try {
        std::string mode;
        int n,cut,period,restarts,sweeps,selective,phase0;
        unsigned seed;
        if(!(std::cin>>mode>>n>>cut>>period>>restarts>>sweeps>>seed>>selective>>phase0)) return 2;
        std::vector<int> cipher(n),start(n),finish(n),mask(n);
        std::vector<double> table(A*A*A),uni(F);
        for(auto& x:cipher)std::cin>>x;
        for(auto& x:start)std::cin>>x;
        for(auto& x:finish)std::cin>>x;
        for(auto& x:mask)std::cin>>x;
        for(int x:mask)if(x!=0 && x!=1)throw std::runtime_error("Invalid score mask");
        for(auto& x:table)std::cin>>x;
        for(auto& x:uni)std::cin>>x;
        if(!std::cin || cut<1 || cut>n || period<1 || period>29 || !finish[cut-1])
            throw std::runtime_error("Invalid input or non-word cut");
        std::vector<int> c(cipher.begin(),cipher.begin()+cut),s(start.begin(),start.begin()+cut),e(finish.begin(),finish.begin()+cut),m(mask.begin(),mask.begin()+cut);
        Decoder decoder{period,(bool)selective,table};
        std::vector<int> bestKey(period,0);double bestScore=NEG;int winning=-1;
        int rotationSweeps=0,rotationMoves=0;std::vector<double> rotationScores;
        if(mode=="oracle" || mode=="rotation_probe") {
            for(auto& k:bestKey)std::cin>>k;
            if(!std::cin) throw std::runtime_error("Missing oracle key");
            bestScore=decoder.run(c,s,e,m,bestKey,phase0,false).score;
            if(mode=="rotation_probe") {
                ++rotationSweeps;
                if(rotate_key(decoder,c,s,e,m,bestKey,phase0,bestScore,rotationScores))++rotationMoves;
            }
        } else if(mode=="fit" || mode=="fit_rotations") {
            if(phase0!=0) throw std::runtime_error("Unknown-key fitting starts at phase zero");
            std::mt19937 rng(seed);
            std::uniform_int_distribution<int> drawKey(0,F-1);
            std::vector<int> init(period,0),order(period);std::iota(order.begin(),order.end(),0);
            for(int phase=0;phase<period;++phase) {
                double top=NEG;
                for(int k=0;k<F;++k) {
                    double score=0;
                    for(int i=phase;i<cut;i+=period)if(m[i])score+=uni[(c[i]-k+F)%F];
                    if(score>top+1e-12){top=score;init[phase]=k;}
                }
            }
            for(int restart=0;restart<restarts;++restart) {
                std::vector<int> key=init;
                if(restart)for(auto& k:key)k=drawKey(rng);
                double current=decoder.run(c,s,e,m,key,0,false).score;
                for(int pass=0;pass<sweeps;++pass) {
                    std::shuffle(order.begin(),order.end(),rng);bool changed=false;
                    for(int slot:order) {
                        int original=key[slot],choice=original;double top=current;
                        for(int k=0;k<F;++k) {
                            if(k==original)continue;
                            key[slot]=k;double score=decoder.run(c,s,e,m,key,0,false).score;
                            if(score>top+1e-10){top=score;choice=k;}
                        }
                        key[slot]=choice;
                        if(choice!=original)changed=true;
                        current=top;
                    }
                    if(mode=="fit_rotations") {
                        ++rotationSweeps;
                        if(rotate_key(decoder,c,s,e,m,key,0,current,rotationScores)) {
                            ++rotationMoves;changed=true;
                        }
                    }
                    if(!changed)break;
                }
                if(current>bestScore+1e-10){bestScore=current;bestKey=key;winning=restart;}
            }
        } else throw std::runtime_error("Unknown mode");
        Path prefix=decoder.run(c,s,e,m,bestKey,phase0,true);
        if(std::abs(prefix.score-bestScore)>1e-7)throw std::runtime_error("Score replay differs");
        std::vector<int> cc(cipher.begin()+cut,cipher.end()),ss(start.begin()+cut,start.end()),ee(finish.begin()+cut,finish.end()),mm(mask.begin()+cut,mask.end());
        Path suffix=decoder.run(cc,ss,ee,mm,bestKey,prefix.end,true);
        std::cout<<std::setprecision(17)<<"{\"key\":";array_json(bestKey);
        std::cout<<",\"winning_restart\":"<<winning<<",\"evaluations\":"<<decoder.evaluations<<",\"prefix\":";
        path_json(prefix);std::cout<<",\"suffix\":";path_json(suffix);
        std::cout<<",\"rotation_sweeps\":"<<rotationSweeps<<",\"rotation_moves\":"<<rotationMoves;
        if(mode=="rotation_probe") {std::cout<<",\"rotation_scores\":";array_json(rotationScores);}
        std::cout<<"}\n";
        return 0;
    } catch(const std::exception& error) {std::cerr<<error.what()<<'\n';return 1;}
}
