// This file was created by the AIR team.

use crate::components::prelude::*;
use crate::components::subroutines::decode_instruction_4b8cf::DecodeInstruction4B8Cf;
use crate::components::subroutines::read_positive_num_bits_36::ReadPositiveNumBits36;
use crate::components::subroutines::read_positive_num_bits_72::ReadPositiveNumBits72;
use crate::components::subroutines::verify_mul_small::VerifyMulSmall;

pub const N_TRACE_COLUMNS: usize = 37;
pub const RELATION_USES_PER_ROW: [RelationUse; 5] = [
    RelationUse {
        relation_id: "MemoryAddressToId",
        uses: 3,
    },
    RelationUse {
        relation_id: "MemoryIdToBig",
        uses: 3,
    },
    RelationUse {
        relation_id: "Opcodes",
        uses: 1,
    },
    RelationUse {
        relation_id: "RangeCheck_11",
        uses: 3,
    },
    RelationUse {
        relation_id: "VerifyInstruction",
        uses: 1,
    },
];

pub struct Eval {
    pub claim: Claim,
    pub common_lookup_elements: relations::CommonLookupElements,
}

#[derive(Copy, Clone, Serialize, Deserialize, CairoSerialize, CairoDeserialize)]
pub struct Claim {
    pub log_size: u32,
}
impl Claim {
    pub fn log_sizes(&self) -> TreeVec<Vec<u32>> {
        let trace_log_sizes = vec![self.log_size; N_TRACE_COLUMNS];
        let interaction_log_sizes = vec![self.log_size; SECURE_EXTENSION_DEGREE * 6];
        TreeVec::new(vec![vec![], trace_log_sizes, interaction_log_sizes])
    }
}

#[derive(Copy, Clone, Serialize, Deserialize, CairoSerialize, CairoDeserialize)]
pub struct InteractionClaim {
    pub claimed_sum: SecureField,
}

pub type Component = FrameworkComponent<Eval>;

impl FrameworkEval for Eval {
    fn log_size(&self) -> u32 {
        self.claim.log_size
    }

    fn max_constraint_log_degree_bound(&self) -> u32 {
        self.log_size() + 1
    }

    #[allow(unused_parens)]
    #[allow(clippy::double_parens)]
    #[allow(non_snake_case)]
    fn evaluate<E: EvalAtRow>(&self, mut eval: E) -> E {
        let M31_1 = E::F::from(M31::from(1));
        let M31_428564188 = E::F::from(M31::from(428564188));
        let input_pc_col0 = eval.next_trace_mask();
        let input_ap_col1 = eval.next_trace_mask();
        let input_fp_col2 = eval.next_trace_mask();
        let offset0_col3 = eval.next_trace_mask();
        let offset1_col4 = eval.next_trace_mask();
        let offset2_col5 = eval.next_trace_mask();
        let dst_base_fp_col6 = eval.next_trace_mask();
        let op0_base_fp_col7 = eval.next_trace_mask();
        let op1_imm_col8 = eval.next_trace_mask();
        let op1_base_fp_col9 = eval.next_trace_mask();
        let ap_update_add_1_col10 = eval.next_trace_mask();
        let mem_dst_base_col11 = eval.next_trace_mask();
        let mem0_base_col12 = eval.next_trace_mask();
        let mem1_base_col13 = eval.next_trace_mask();
        let dst_id_col14 = eval.next_trace_mask();
        let dst_limb_0_col15 = eval.next_trace_mask();
        let dst_limb_1_col16 = eval.next_trace_mask();
        let dst_limb_2_col17 = eval.next_trace_mask();
        let dst_limb_3_col18 = eval.next_trace_mask();
        let dst_limb_4_col19 = eval.next_trace_mask();
        let dst_limb_5_col20 = eval.next_trace_mask();
        let dst_limb_6_col21 = eval.next_trace_mask();
        let dst_limb_7_col22 = eval.next_trace_mask();
        let op0_id_col23 = eval.next_trace_mask();
        let op0_limb_0_col24 = eval.next_trace_mask();
        let op0_limb_1_col25 = eval.next_trace_mask();
        let op0_limb_2_col26 = eval.next_trace_mask();
        let op0_limb_3_col27 = eval.next_trace_mask();
        let op1_id_col28 = eval.next_trace_mask();
        let op1_limb_0_col29 = eval.next_trace_mask();
        let op1_limb_1_col30 = eval.next_trace_mask();
        let op1_limb_2_col31 = eval.next_trace_mask();
        let op1_limb_3_col32 = eval.next_trace_mask();
        let carry_1_col33 = eval.next_trace_mask();
        let carry_3_col34 = eval.next_trace_mask();
        let carry_5_col35 = eval.next_trace_mask();
        let enabler_col36 = eval.next_trace_mask();

        #[allow(clippy::unused_unit)]
        #[allow(unused_variables)]
        let [decode_instruction_4b8cf_output_tmp_9d1ad_11_offset0, decode_instruction_4b8cf_output_tmp_9d1ad_11_offset1, decode_instruction_4b8cf_output_tmp_9d1ad_11_offset2, decode_instruction_4b8cf_output_tmp_9d1ad_11_op1_base_ap] =
            DecodeInstruction4B8Cf::evaluate(
                [input_pc_col0.clone()],
                offset0_col3.clone(),
                offset1_col4.clone(),
                offset2_col5.clone(),
                dst_base_fp_col6.clone(),
                op0_base_fp_col7.clone(),
                op1_imm_col8.clone(),
                op1_base_fp_col9.clone(),
                ap_update_add_1_col10.clone(),
                &self.common_lookup_elements,
                &mut eval,
            );
        // if imm then offset2 is 1.
        eval.add_constraint(
            (op1_imm_col8.clone()
                * (M31_1.clone() - decode_instruction_4b8cf_output_tmp_9d1ad_11_offset2.clone())),
        );
        // mem_dst_base.
        eval.add_constraint(
            (mem_dst_base_col11.clone()
                - ((dst_base_fp_col6.clone() * input_fp_col2.clone())
                    + ((M31_1.clone() - dst_base_fp_col6.clone()) * input_ap_col1.clone()))),
        );
        // mem0_base.
        eval.add_constraint(
            (mem0_base_col12.clone()
                - ((op0_base_fp_col7.clone() * input_fp_col2.clone())
                    + ((M31_1.clone() - op0_base_fp_col7.clone()) * input_ap_col1.clone()))),
        );
        // mem1_base.
        eval.add_constraint(
            (mem1_base_col13.clone()
                - (((op1_imm_col8.clone() * input_pc_col0.clone())
                    + (op1_base_fp_col9.clone() * input_fp_col2.clone()))
                    + (decode_instruction_4b8cf_output_tmp_9d1ad_11_op1_base_ap.clone()
                        * input_ap_col1.clone()))),
        );
        ReadPositiveNumBits72::evaluate(
            [(mem_dst_base_col11.clone()
                + decode_instruction_4b8cf_output_tmp_9d1ad_11_offset0.clone())],
            dst_id_col14.clone(),
            dst_limb_0_col15.clone(),
            dst_limb_1_col16.clone(),
            dst_limb_2_col17.clone(),
            dst_limb_3_col18.clone(),
            dst_limb_4_col19.clone(),
            dst_limb_5_col20.clone(),
            dst_limb_6_col21.clone(),
            dst_limb_7_col22.clone(),
            &self.common_lookup_elements,
            &mut eval,
        );
        ReadPositiveNumBits36::evaluate(
            [(mem0_base_col12.clone()
                + decode_instruction_4b8cf_output_tmp_9d1ad_11_offset1.clone())],
            op0_id_col23.clone(),
            op0_limb_0_col24.clone(),
            op0_limb_1_col25.clone(),
            op0_limb_2_col26.clone(),
            op0_limb_3_col27.clone(),
            &self.common_lookup_elements,
            &mut eval,
        );
        ReadPositiveNumBits36::evaluate(
            [(mem1_base_col13.clone()
                + decode_instruction_4b8cf_output_tmp_9d1ad_11_offset2.clone())],
            op1_id_col28.clone(),
            op1_limb_0_col29.clone(),
            op1_limb_1_col30.clone(),
            op1_limb_2_col31.clone(),
            op1_limb_3_col32.clone(),
            &self.common_lookup_elements,
            &mut eval,
        );
        VerifyMulSmall::evaluate(
            [
                op0_limb_0_col24.clone(),
                op0_limb_1_col25.clone(),
                op0_limb_2_col26.clone(),
                op0_limb_3_col27.clone(),
                op1_limb_0_col29.clone(),
                op1_limb_1_col30.clone(),
                op1_limb_2_col31.clone(),
                op1_limb_3_col32.clone(),
                dst_limb_0_col15.clone(),
                dst_limb_1_col16.clone(),
                dst_limb_2_col17.clone(),
                dst_limb_3_col18.clone(),
                dst_limb_4_col19.clone(),
                dst_limb_5_col20.clone(),
                dst_limb_6_col21.clone(),
                dst_limb_7_col22.clone(),
            ],
            carry_1_col33.clone(),
            carry_3_col34.clone(),
            carry_5_col35.clone(),
            &self.common_lookup_elements,
            &mut eval,
        );
        // Enabler is a bit.
        eval.add_constraint(
            ((enabler_col36.clone() * enabler_col36.clone()) - enabler_col36.clone()),
        );
        eval.add_to_relation(RelationEntry::new(
            &self.common_lookup_elements,
            E::EF::from(enabler_col36.clone()),
            &[
                M31_428564188.clone(),
                input_pc_col0.clone(),
                input_ap_col1.clone(),
                input_fp_col2.clone(),
            ],
        ));

        eval.add_to_relation(RelationEntry::new(
            &self.common_lookup_elements,
            -E::EF::from(enabler_col36.clone()),
            &[
                M31_428564188.clone(),
                ((input_pc_col0.clone() + M31_1.clone()) + op1_imm_col8.clone()),
                (input_ap_col1.clone() + ap_update_add_1_col10.clone()),
                input_fp_col2.clone(),
            ],
        ));

        eval.finalize_logup_in_pairs();
        eval
    }
}

#[cfg(test)]
mod tests {
    use num_traits::Zero;
    use rand::rngs::SmallRng;
    use rand::{Rng, SeedableRng};
    use stwo::core::fields::qm31::QM31;
    use stwo_constraint_framework::expr::ExprEvaluator;

    use super::*;
    use crate::components::constraints_regression_test_values::MUL_OPCODE_SMALL;

    #[test]
    fn mul_opcode_small_constraints_regression() {
        let mut rng = SmallRng::seed_from_u64(0);
        let eval = Eval {
            claim: Claim { log_size: 4 },
            common_lookup_elements: relations::CommonLookupElements::dummy(),
        };
        let expr_eval = eval.evaluate(ExprEvaluator::new());
        let assignment = expr_eval.random_assignment();

        let mut sum = QM31::zero();
        for c in expr_eval.constraints {
            sum += c.assign(&assignment) * rng.gen::<QM31>();
        }

        MUL_OPCODE_SMALL.assert_debug_eq(&sum);
    }
}
