// Integer transfer inequalities and rectangle coverage for the period-two polynomial.
// Compile with assertions enabled and a C++17 compiler supporting 128-bit integers.
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <limits>
#include <map>
#include <utility>
#include <vector>

#ifdef NDEBUG
#error Assertions must be enabled for certificate verification
#endif

using Int = std::int64_t;
using Wide = __int128_t;
using Vector = std::vector<Int>;
using Branches = std::array<Vector, 2>;
using Vertices = std::map<std::pair<int, int>, Int>;

constexpr Int turn = 65536, billion = 1000000000, trig_scale = 100000000;
constexpr Int coefficient_scale = 64000000, grid = 1024;
constexpr Int a_10000 = 2063, b_10000 = 269, d_10000 = 616, t_100 = 73;
constexpr Int gamma_10000 = 4002, projection_limit = 219110000;

Int narrow(Wide x) {
    assert(x >= std::numeric_limits<Int>::min() && x <= std::numeric_limits<Int>::max());
    return static_cast<Int>(x);
}

Int floor_div(Wide x, Wide d) {
    assert(d > 0);
    return narrow(x >= 0 ? x/d : -((-x+d-1)/d));
}

Int ceil_div(Wide x, Wide d) {
    return narrow(-Wide(floor_div(-x, d)));
}

struct Tables {
    std::array<std::int32_t,turn> trig;
    // Each pair contains an upper bound for 10^7 exp(b/10^4)/2 and a
    // lower bound for 10^10 exp(b/10^4). Blocks are nonnegative and negative b.
    std::array<std::vector<std::array<std::uint64_t,2>>,2> exp;

    explicit Tables(const char* path) {
        static_assert(sizeof(std::array<std::uint64_t,2>) == 16);
        const std::uint16_t endian = 1;
        assert(*reinterpret_cast<const unsigned char*>(&endian) == 1);
        std::ifstream input(path, std::ios::binary);
        assert(input);
        input.read(reinterpret_cast<char*>(trig.data()), sizeof(trig));
        for (auto& block : exp) {
            block.resize(150001);
            input.read(reinterpret_cast<char*>(block.data()), 16*block.size());
        }
        assert(input && trig[0] == trig_scale);
        assert(input.peek() == std::ifstream::traits_type::eof());
    }

    Int cosine(Int angle) const {
        return trig[(angle%turn + turn)%turn];
    }

    const auto& exponential(Int bucket) const {
        assert(bucket >= -150000 && bucket <= 150000);
        return exp[bucket < 0][std::abs(bucket)];
    }
};

struct Row {
    int angle, s, q, cells, lambda, kappa, tilt;
    Int bound;
};

Branches branch_weights(const Tables& data, const Row& row, Int sign) {
    // The two cosine/sine amplitudes at phase theta/2 in units of coefficient_scale.
    const Int c = coefficient_scale;
    const Int cos_half = row.s*(2*c/grid) + sign*row.q*(2*t_100*c/(100*grid));
    const Int sin_half = -row.lambda*(2*c/10000) - sign*row.kappa*(2*t_100*c/1000000);
    const Int cos_full = -a_10000*(c/10000), cos_third = -d_10000*(c/10000);
    const Int phase = turn*row.angle/128;
    const Int allowance = ceil_div(Wide(314159265359LL)*trig_scale,
                                   200000000000LL*row.cells);
    const Int first = std::abs(cos_half) + std::abs(sin_half) + std::abs(cos_full);
    // Two cosine table units per term, plus pi/(2n) times a derivative bound.
    const Int error = 2*(first+std::abs(cos_third)) + allowance*(first+3*std::abs(cos_third));
    Branches weights;
    for (int branch = 0; branch < 2; ++branch) {
        weights[branch].resize(row.cells);
        for (int j = 0; j < row.cells; ++j) {
            const Int x = (2*j+1)*(turn/(4*row.cells)) + branch*turn/2;
            const Int midpoint = cos_half*data.cosine(x-phase/2)
                              + sin_half*data.cosine(x-phase/2-turn/4)
                              + cos_full*data.cosine(x-phase)
                              + cos_third*data.cosine(3*x-phase);
            const Int bucket = ceil_div(Wide(row.tilt)*(midpoint+error), Wide(c)*trig_scale);
            weights[branch][j] = narrow(data.exponential(bucket)[0]);
        }
    }
    return weights;
}

Wide action_row(const Branches& weights, const Vector& h, int j) {
    const int n = static_cast<int>(h.size());
    return Wide(weights[0][j])*h[j/2] + Wide(weights[1][j])*h[(n+j)/2];
}

void propose_vector(const Branches& weights, const Vector& input, Vector& output,
                    std::vector<Wide>& numerators) {
    Wide largest = 0;
    for (int j = 0; j < static_cast<int>(input.size()); ++j) {
        numerators[j] = action_row(weights, input, j);
        largest = std::max(largest, numerators[j]);
    }
    assert(largest > 0);
    for (int j = 0; j < static_cast<int>(input.size()); ++j)
        output[j] = std::max<Int>(1, narrow(numerators[j]*10000000000LL/largest));
}

// Upper bound on 10^8 times the largest exact row ratio. The branch weights
// include the factor 1/2 and are scaled by 10^7.
Int upper_ratio(const Branches& weights, const Vector& h_in, const Vector& h_out) {
    Int result = 0;
    for (int j = 0; j < static_cast<int>(h_in.size()); ++j) {
        const Wide numerator = action_row(weights,h_in,j);
        result = std::max(result, ceil_div(numerator*100000000, Wide(10000000)*h_out[j]));
    }
    return result;
}

bool pressure_holds(const Tables& data, const Row& r) {
    assert(r.angle >= 0 && r.angle <= 64 && r.s >= -grid && r.s <= grid);
    assert(r.q >= 0 && r.q <= grid && r.tilt > 0 && r.tilt <= 600000);
    assert(r.lambda >= -10000 && r.lambda <= 10000 && r.kappa >= -10000 && r.kappa <= 10000);
    assert(r.cells >= 128 && r.cells <= 16384 && turn%(4*r.cells) == 0);
    assert(r.bound >= -10*billion && r.bound <= 10*billion);

    const auto plus = branch_weights(data,r,1), minus = branch_weights(data,r,-1);
    Vector h0(r.cells,10000000000LL), h1(r.cells);
    std::vector<Wide> work(r.cells);
    for (int j = 0; j < 25; ++j) {
        propose_vector(plus,h0,h1,work);
        propose_vector(minus,h1,h0,work);
    }
    propose_vector(plus,h0,h1,work);
    const Wide product = Wide(upper_ratio(plus,h0,h1))*upper_ratio(minus,h1,h0);

    // Lower bound on 10^9 (b_* + s^2 + t*q^2 - lambda^2 - t*kappa^2 + b*cos(theta)).
    const Int support = r.bound
        + floor_div(Wide(billion)*r.s*r.s, grid*grid)
        + floor_div(Wide(billion)*t_100*r.q*r.q, 100*grid*grid)
        - ceil_div(Wide(billion)*r.lambda*r.lambda, 100000000)
        - ceil_div(Wide(billion)*t_100*r.kappa*r.kappa, 10000000000LL)
        + floor_div(Wide(billion)*b_10000*(data.cosine(turn*r.angle/128)-2),
                    10000*trig_scale);
    const Int bucket = floor_div(Wide(2)*r.tilt*support, billion)
                     - ceil_div(Wide(2)*gamma_10000*69315, 100000);
    // Product scale is 10^16, exponential lower table scale is 10^10.
    return product <= Wide(data.exponential(bucket)[1])*1000000;
}

Int cover(const Vertices& vertices, int x0, int x1, int y0, int y1) {
    Int high = -10*billion;
    for (int x : {x0,x1}) for (int y : {y0,y1}) {
        const auto found = vertices.find({x,y});
        assert(found != vertices.end());
        high = std::max(high, found->second);
    }
    const Int dx = x1-x0, dy = y1-y0;
    const Int cost = ceil_div(Wide(billion)*(100*dx*dx+t_100*dy*dy), 400*grid*grid);
    if (high+cost <= projection_limit)
        return high+cost;
    assert(dx > 3 || dy > 3);
    if (dx >= dy) {
        const int mid = (x0+x1)/2;
        return std::max(cover(vertices,x0,mid,y0,y1), cover(vertices,mid,x1,y0,y1));
    }
    const int mid = (y0+y1)/2;
    return std::max(cover(vertices,x0,x1,y0,mid), cover(vertices,x0,x1,mid,y1));
}

int main(int argc, char** argv) {
    assert(argc == 3);
    Tables tables(argv[1]);
    std::ifstream input(argv[2]);
    assert(input);
    std::array<Vertices,65> vertices;
    Int rows = 0, worst = 0;
    Row r;
    while (input >> r.angle >> r.s >> r.q >> r.cells >> r.lambda >> r.kappa >> r.tilt >> r.bound) {
        r.bound = narrow(Wide(r.bound)+10000); // column 8 plus 10^-5 in actual units
        if (!pressure_holds(tables,r)) {
            std::cerr << "Failed vertex at angle " << r.angle << ", coordinates "
                      << r.s << ", " << r.q << "\n";
            return 1;
        }
        assert(vertices[r.angle].emplace(std::make_pair(r.s,r.q),r.bound).second);
        ++rows;
    }
    assert(input.eof());
    for (int j = 0; j <= 64; ++j) {
        const Int top = cover(vertices[j],-grid,grid,0,grid);
        worst = std::max(worst,top);
        std::cout << "Angle " << j << " vertices " << vertices[j].size()
                  << " projection upper (1e-9) " << top << "\n";
    }
    assert(rows == 5703 && worst <= 219097314);
    std::cout << "PASS integer witnesses " << rows
              << " certified projection upper_1e9 " << worst << std::endl;
}
