// This file was created by the AIR team.

use crate::components::prelude::*;
use crate::components::subroutines::decode_instruction_d2a10::DecodeInstructionD2A10;
use crate::components::subroutines::range_check_29::RangeCheck29;
use crate::components::subroutines::read_small::ReadSmall;

pub const N_TRACE_COLUMNS: usize = 17;
pub const RELATION_USES_PER_ROW: [RelationUse; 6] = [
    RelationUse {
        relation_id: "MemoryAddressToId",
        uses: 1,
    },
    RelationUse {
        relation_id: "MemoryIdToBig",
        uses: 1,
    },
    RelationUse {
        relation_id: "Opcodes",
        uses: 1,
    },
    RelationUse {
        relation_id: "RangeCheck_11",
        uses: 1,
    },
    RelationUse {
        relation_id: "RangeCheck_18",
        uses: 1,
    },
    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 * 4];
        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 offset2_col3 = eval.next_trace_mask();
        let op1_imm_col4 = eval.next_trace_mask();
        let op1_base_fp_col5 = eval.next_trace_mask();
        let mem1_base_col6 = eval.next_trace_mask();
        let op1_id_col7 = eval.next_trace_mask();
        let msb_col8 = eval.next_trace_mask();
        let mid_limbs_set_col9 = eval.next_trace_mask();
        let op1_limb_0_col10 = eval.next_trace_mask();
        let op1_limb_1_col11 = eval.next_trace_mask();
        let op1_limb_2_col12 = eval.next_trace_mask();
        let remainder_bits_col13 = eval.next_trace_mask();
        let partial_limb_msb_col14 = eval.next_trace_mask();
        let range_check_29_bot11bits_col15 = eval.next_trace_mask();
        let enabler_col16 = eval.next_trace_mask();

        #[allow(clippy::unused_unit)]
        #[allow(unused_variables)]
        let [decode_instruction_d2a10_output_tmp_c921e_6_offset2, decode_instruction_d2a10_output_tmp_c921e_6_op1_base_ap] =
            DecodeInstructionD2A10::evaluate(
                [input_pc_col0.clone()],
                offset2_col3.clone(),
                op1_imm_col4.clone(),
                op1_base_fp_col5.clone(),
                &self.common_lookup_elements,
                &mut eval,
            );
        // if imm then offset2 is 1.
        eval.add_constraint(
            (op1_imm_col4.clone()
                * (M31_1.clone() - decode_instruction_d2a10_output_tmp_c921e_6_offset2.clone())),
        );
        // mem1_base.
        eval.add_constraint(
            (mem1_base_col6.clone()
                - (((op1_imm_col4.clone() * input_pc_col0.clone())
                    + (op1_base_fp_col5.clone() * input_fp_col2.clone()))
                    + (decode_instruction_d2a10_output_tmp_c921e_6_op1_base_ap.clone()
                        * input_ap_col1.clone()))),
        );
        #[allow(clippy::unused_unit)]
        #[allow(unused_variables)]
        let [read_small_output_tmp_c921e_16_limb_0] = ReadSmall::evaluate(
            [(mem1_base_col6.clone()
                + decode_instruction_d2a10_output_tmp_c921e_6_offset2.clone())],
            op1_id_col7.clone(),
            msb_col8.clone(),
            mid_limbs_set_col9.clone(),
            op1_limb_0_col10.clone(),
            op1_limb_1_col11.clone(),
            op1_limb_2_col12.clone(),
            remainder_bits_col13.clone(),
            partial_limb_msb_col14.clone(),
            &self.common_lookup_elements,
            &mut eval,
        );
        let next_ap_tmp_c921e_17 = eval.add_intermediate(
            (input_ap_col1.clone() + read_small_output_tmp_c921e_16_limb_0.clone()),
        );
        RangeCheck29::evaluate(
            [next_ap_tmp_c921e_17.clone()],
            range_check_29_bot11bits_col15.clone(),
            &self.common_lookup_elements,
            &mut eval,
        );
        // Enabler is a bit.
        eval.add_constraint(
            ((enabler_col16.clone() * enabler_col16.clone()) - enabler_col16.clone()),
        );
        eval.add_to_relation(RelationEntry::new(
            &self.common_lookup_elements,
            E::EF::from(enabler_col16.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_col16.clone()),
            &[
                M31_428564188.clone(),
                (input_pc_col0.clone() + (M31_1.clone() + op1_imm_col4.clone())),
                next_ap_tmp_c921e_17.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::ADD_AP_OPCODE;

    #[test]
    fn add_ap_opcode_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>();
        }

        ADD_AP_OPCODE.assert_debug_eq(&sum);
    }
}
