use crate::error::{Error, Result};
use crate::hwid::{detect_os, get_hwid};
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use ed25519_dalek::{Signature, VerifyingKey};
use serde_json::{Map, Value};
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn verify_offline_license(public_key: &str, token_or_path: &str, hwid: Option<&str>, expected_product_id: Option<&str>) -> Result<Map<String, Value>> {
let mut token = token_or_path.to_string();
if !token.contains('\n') && token.len() < 4096 && Path::new(&token).is_file() {
token = std::fs::read_to_string(&token).map_err(|_| Error::Signature("License file could not be read".into()))?;
}
let token = token.trim();
let bad = || Error::Signature("Invalid or tampered license file".into());
let mut parts = token.split('.');
let (Some(payload_b64), Some(sig_b64), None) = (parts.next(), parts.next(), parts.next()) else { return Err(bad()) };
let key_bytes: [u8; 32] = B64.decode(public_key.trim()).map_err(|_| bad())?.try_into().map_err(|_| bad())?;
let key = VerifyingKey::from_bytes(&key_bytes).map_err(|_| bad())?;
let sig = Signature::from_slice(&B64.decode(sig_b64).map_err(|_| bad())?).map_err(|_| bad())?;
key.verify_strict(payload_b64.as_bytes(), &sig).map_err(|_| bad())?;
let data = match serde_json::from_slice::<Value>(&B64.decode(payload_b64).map_err(|_| bad())?) {
Ok(Value::Object(m)) => m,
_ => return Err(bad()),
};
if let Some(want) = expected_product_id {
let got = data.get("product_id").and_then(Value::as_str).unwrap_or("");
if got != want { return Err(Error::ProductMismatch { expected: want.to_string(), actual: got.to_string() }); }
}
match data.get("expires_at") {
None | Some(Value::Null) => {}
Some(v) if v.as_i64() == Some(0) => {}
Some(v) => {
let exp = v.as_f64().ok_or_else(|| Error::InvalidLicense { status: 0, message: "License file has an unreadable expiry".into() })?;
let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0);
if now > exp { return Err(Error::InvalidLicense { status: 0, message: "License file has expired".into() }); }
}
}
let me = hwid.map(str::to_string).unwrap_or_else(get_hwid);
if let Some(h) = data.get("hwid").and_then(Value::as_str).filter(|h| !h.is_empty()) {
if h != me { return Err(Error::InvalidLicense { status: 0, message: "License file is not valid for this machine".into() }); }
}
if let Some(os) = data.get("os_lock").and_then(Value::as_str).filter(|o| !o.is_empty()) {
if os != detect_os() { return Err(Error::InvalidLicense { status: 0, message: "License file is not valid on this operating system".into() }); }
}
Ok(data)
}