// SPDX-License-Identifier: MIT
// A synthetic four-neuron control experiment using only FlyBrain's installed API.
#include <flybrain/brain.hpp>
#include <algorithm>
#include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

namespace {
constexpr double dt=0.02, speed=0.12, radius=0.045;
constexpr std::size_t horizon=600, ticks=20;
struct Point { double x,y; };
struct Frame {
    std::size_t step;
    double x,y,angle,left,right;
    std::uint64_t motor_left,motor_right;
    bool operator==(const Frame&) const = default;
};
struct Trial {
    std::size_t scenario;
    std::string controller;
    Point target;
    double initial_angle;
    bool reached=false;
    std::size_t steps=0;
    std::uint64_t output_spikes=0;
    std::vector<Frame> frames;
};
std::shared_ptr<flybrain::Network> circuit(bool connected=true) {
    return std::make_shared<flybrain::Network>(4,
        connected?std::vector<flybrain::Edge>{{0,2,28,1},{1,3,28,1}}:std::vector<flybrain::Edge>{},
        std::vector<std::uint64_t>{1001,1002,1003,1004});
}
flybrain::Brain brain(bool connected=true) {
    return {circuit(connected),{{"left_sensor",{1001},3.0F},{"right_sensor",{1002},3.0F}},
                              {{"left_motor",{1003}},{"right_motor",{1004}}}};
}
std::array<float,2> sense(Point position,Point target,double angle) {
    const double bearing=std::atan2(target.y-position.y,target.x-position.x)-angle;
    const double difference=std::sin(bearing);
    return {static_cast<float>(0.5+0.5*difference),static_cast<float>(0.5-0.5*difference)};
}
Trial run(std::size_t scenario, const std::string& controller) {
    constexpr std::array<Point,3> targets{{{0.82,0.50},{0.20,0.75},{0.30,0.15}}};
    constexpr std::array<double,6> angles{{-2.5,-1.2,-0.3,0.3,1.2,2.5}};
    const auto target=targets.at(scenario/angles.size());
    double angle=angles.at(scenario%angles.size());
    auto neural=brain(controller!="disconnected");
    Trial trial{scenario,controller,target,angle,false,0,0,{}};
    Point position{0.5,0.5};
    trial.frames.push_back({0,position.x,position.y,angle,0,0,0,0});
    for(std::size_t step=1;step<=horizon;++step) {
        const auto inputs=sense(position,target,angle);
        std::uint64_t left=0,right=0;
        double yaw=0;
        if(controller=="rule") yaw=3.0*static_cast<double>(inputs[0]-inputs[1]);
        else {
            const auto output=neural.advance(inputs,ticks);
            left=output[0].spikes;right=output[1].spikes;
            yaw=0.8*(static_cast<double>(left)-static_cast<double>(right));
            trial.output_spikes+=left+right;
        }
        yaw=std::clamp(yaw,-3.0,3.0);
        angle=std::remainder(angle+yaw*dt,2*std::acos(-1.0));
        position.x=std::clamp(position.x+speed*dt*std::cos(angle),0.02,0.98);
        position.y=std::clamp(position.y+speed*dt*std::sin(angle),0.02,0.98);
        const double distance=std::hypot(position.x-target.x,position.y-target.y);
        trial.steps=step;trial.reached=distance<=radius;
        if(step%5==0 || trial.reached || step==horizon)
            trial.frames.push_back({step,position.x,position.y,angle,inputs[0],inputs[1],left,right});
        if(trial.reached) break;
    }
    return trial;
}
void require(bool condition,const char* message) { if(!condition) throw std::runtime_error(message); }
void verify() {
    auto a=brain(),b=brain(),empty=brain(false);
    std::uint64_t total_left=0,total_right=0;
    for(int window=0;window<30;++window) {
        const auto left=a.advance(std::array<float,2>{1,0},ticks);
        const auto right=b.advance(std::array<float,2>{0,1},ticks);
        const auto off=empty.advance(std::array<float,2>{1,1},ticks);
        require(left[0].spikes==right[1].spikes && left[1].spikes==right[0].spikes,"mirror symmetry");
        require(off[0].spikes==0 && off[1].spikes==0,"disconnected motor output");
        total_left+=left[0].spikes;total_right+=left[1].spikes;
    }
    require(total_left>0 && total_right==0,"sensory-to-motor transmission");
    std::size_t baseline_hits=0,neural_hits=0;
    for(std::size_t scenario=0;scenario<18;++scenario) for(const auto* kind:{"rule","neural","disconnected"}) {
        const auto trial=run(scenario,kind),repeat=run(scenario,kind);
        require(trial.frames==repeat.frames,"same-build deterministic replay");
        require(trial.reached==repeat.reached && trial.steps==repeat.steps,"repeat outcome");
        for(const auto& f:trial.frames) {
            require(std::isfinite(f.x) && std::isfinite(f.y) && std::isfinite(f.angle),"finite trajectory");
            require(f.x>=0.02 && f.x<=0.98 && f.y>=0.02 && f.y<=0.98,"world bounds");
        }
        const auto& last=trial.frames.back();
        require(trial.reached==(std::hypot(last.x-trial.target.x,last.y-trial.target.y)<=radius),"reach predicate");
        if(trial.controller=="disconnected") require(trial.output_spikes==0,"ablation spikes");
        if(trial.controller=="rule" && trial.reached) ++baseline_hits;
        if(trial.controller=="neural" && trial.reached) ++neural_hits;
    }
    require(baseline_hits==18,"baseline failed the fixed integration scenarios");
    require(neural_hits>0,"neural controller never reached a beacon");
    std::cout<<"Mirror, ablation, deterministic replay, bounds and reach checks passed; neural "<<neural_hits<<"/18, rule "<<baseline_hits<<"/18\n";
}
void emit(const Trial& t) {
    std::cout<<"{\"scenario\":"<<t.scenario<<",\"controller\":\""<<t.controller<<"\",\"target\":["<<t.target.x<<','<<t.target.y
             <<"],\"initial_angle\":"<<t.initial_angle<<",\"reached\":"<<(t.reached?"true":"false")<<",\"steps\":"<<t.steps
             <<",\"output_spikes\":"<<t.output_spikes<<",\"frames\":[";
    bool first=true;
    for(const auto& f:t.frames) {
        if(!first) std::cout<<',';
        first=false;
        std::cout<<'['<<f.step<<','<<f.x<<','<<f.y<<','<<f.angle<<','<<f.left<<','<<f.right<<','<<f.motor_left<<','<<f.motor_right<<']';
    }
    std::cout<<"]}\n";
}
}
int main(int argc,char** argv) {
    try {
        if(argc==2 && std::string(argv[1])=="--verify") {verify();return 0;}
        if(argc!=1) throw std::runtime_error("usage: flybrain_arena [--verify]");
        std::cout<<std::setprecision(12);
        for(std::size_t scenario=0;scenario<18;++scenario)
            for(const auto* kind:{"rule","neural","disconnected"}) emit(run(scenario,kind));
    } catch(const std::exception& error) {std::cerr<<error.what()<<'\n';return 1;}
}
