use solana_program::pubkey::Pubkey;

use crate::pyra::get_vault;
use crate::DRIFT_PROGRAM_ID;

/// Derive the Drift user PDA for a Pyra vault.
///
/// `owner` is the end user's wallet pubkey. The Pyra vault is derived
/// internally — do NOT pass the vault.
pub fn get_drift_user(owner: &Pubkey, sub_account_id: u16) -> Pubkey {
    let vault = get_vault(owner);
    let (pubkey, _) = Pubkey::find_program_address(
        &[
            b"user",
            vault.as_ref(),
            sub_account_id.to_le_bytes().as_ref(),
        ],
        &DRIFT_PROGRAM_ID,
    );
    pubkey
}

/// Derive the Drift user-stats PDA for a Pyra vault.
///
/// `owner` is the end user's wallet pubkey. The Pyra vault is derived
/// internally — do NOT pass the vault.
pub fn get_drift_user_stats(owner: &Pubkey) -> Pubkey {
    let vault = get_vault(owner);
    let (pubkey, _) =
        Pubkey::find_program_address(&[b"user_stats", vault.as_ref()], &DRIFT_PROGRAM_ID);
    pubkey
}

pub fn get_drift_state() -> Pubkey {
    let (pubkey, _) = Pubkey::find_program_address(&[b"drift_state"], &DRIFT_PROGRAM_ID);
    pubkey
}

pub fn get_drift_signer() -> Pubkey {
    let (pubkey, _) = Pubkey::find_program_address(&[b"drift_signer"], &DRIFT_PROGRAM_ID);
    pubkey
}

/// Derive the Drift spot market vault PDA for a Pyra asset ID.
///
/// Returns `None` if the asset has no Drift market index.
pub fn get_drift_spot_market_vault(asset_id: pyra_tokens::AssetId) -> Option<Pubkey> {
    let market_index = asset_id.drift_market_index()?;
    let (pubkey, _) = Pubkey::find_program_address(
        &[b"spot_market_vault", market_index.to_le_bytes().as_ref()],
        &DRIFT_PROGRAM_ID,
    );
    Some(pubkey)
}

/// Derive the Drift spot market PDA for a Pyra asset ID.
///
/// Returns `None` if the asset has no Drift market index.
pub fn get_drift_spot_market(asset_id: pyra_tokens::AssetId) -> Option<Pubkey> {
    let market_index = asset_id.drift_market_index()?;
    let (pubkey, _) = Pubkey::find_program_address(
        &[b"spot_market", market_index.to_le_bytes().as_ref()],
        &DRIFT_PROGRAM_ID,
    );
    Some(pubkey)
}
