use anchor_lang::prelude::*;

declare_id!("2EeLEM1JQbuZN3DV1Unmi8vsypqvdnzD9p7hS4wqbqAR");

const MAX_SIGNATURE_BYTES: usize = 2420; // Dilithium-2 signature is 2420 bytes

#[program]
pub mod dilithium_attestor {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        let deployment_authorized = false;
        require!(deployment_authorized, DilithiumError::BootstrapDisabled);
        let state = &mut ctx.accounts.attestor_state;
        state.authority = ctx.accounts.authority.key();
        state.total_attestations = 0;
        state.created_at = Clock::get()?.unix_timestamp;
        Ok(())
    }

    pub fn submit_attestation(
        _ctx: Context<SubmitAttestation>,
        _attestation_hash: [u8; 32],
        _signature_bytes: Vec<u8>,
    ) -> Result<()> {
        // Storing attacker-provided bytes as a "Dilithium attestation" is not
        // verification. ML-DSA verification has not been implemented or
        // independently reviewed for this BPF target, so V3 rejects the
        // operation atomically instead of creating a misleading trust record.
        err!(DilithiumError::VerificationUnavailable)
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init,
        payer = authority,
        space = 8 + 32 + 8 + 8,
        seeds = [b"dilithium_attestor"],
        bump
    )]
    pub attestor_state: Account<'info, AttestorState>,
    #[account(mut)]
    pub authority: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
#[instruction(attestation_hash: [u8; 32], signature_bytes: Vec<u8>)]
pub struct SubmitAttestation<'info> {
    #[account(
        mut,
        seeds = [b"dilithium_attestor"],
        bump
    )]
    pub attestor_state: Account<'info, AttestorState>,
    #[account(
        init,
        payer = agent,
        space = 8 + 32 + 32 + 4 + MAX_SIGNATURE_BYTES + 8,
        seeds = [b"dilithium", agent.key().as_ref(), attestation_hash.as_ref()],
        bump
    )]
    pub attestation_record: Account<'info, DilithiumRecord>,
    #[account(mut)]
    pub agent: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct AttestorState {
    pub authority: Pubkey,
    pub total_attestations: u64,
    pub created_at: i64,
}

#[account]
pub struct DilithiumRecord {
    pub agent: Pubkey,
    pub attestation_hash: [u8; 32],
    pub signature_bytes: Vec<u8>,
    pub attested_at: i64,
}

#[event]
pub struct DilithiumAttested {
    pub agent: Pubkey,
    pub attestation_hash: [u8; 32],
    pub attested_at: i64,
}

#[error_code]
pub enum DilithiumError {
    #[msg("Signature bytes exceed maximum size")]
    SignatureTooLarge,
    #[msg("ML-DSA verification is unavailable; attestation submission is fail-closed")]
    VerificationUnavailable,
    #[msg("Bootstrap is disabled until a source-backed partner authority design is approved")]
    BootstrapDisabled,
}
