/// Load cookies from a JSON array file or Netscape cookie file.
pub fn load_cookies(path: &str) -> Result<Vec<serde_json::Value>, String> {
    let expanded = if let Some(suffix) = path.strip_prefix('~') {
        let home = std::env::var("HOME").unwrap_or_default();
        format!("{}{}", home, suffix)
    } else {
        path.to_string()
    };

    let content =
        std::fs::read_to_string(&expanded).map_err(|e| format!("cannot read {expanded}: {e}"))?;

    // Try JSON first
    if content.trim_start().starts_with('[') || content.trim_start().starts_with('{') {
        return serde_json::from_str::<Vec<serde_json::Value>>(&content)
            .map_err(|e| format!("JSON parse error: {e}"));
    }

    // Netscape format
    parse_netscape_cookies(&content)
}

/// Parse Netscape HTTP Cookie File format.
/// Columns: domain  subdomain_flag  path  secure  expiry  name  value
fn parse_netscape_cookies(content: &str) -> Result<Vec<serde_json::Value>, String> {
    let mut cookies = Vec::new();
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let parts: Vec<&str> = line.splitn(7, '\t').collect();
        if parts.len() < 6 {
            continue;
        }
        let domain = parts[0];
        // parts[1] = subdomain flag (already reflected in domain with leading dot)
        let path = parts[2];
        let secure = parts[3].eq_ignore_ascii_case("true");
        let expiry: i64 = parts[4].parse().unwrap_or(0);
        let name = parts[5];
        let value = if parts.len() > 6 { parts[6] } else { "" };

        let mut c = serde_json::json!({
            "name":   name,
            "value":  value,
            "domain": domain,
            "path":   path,
            "secure": secure,
            "httpOnly": false,
        });
        if expiry > 0 {
            c["expires"] = serde_json::json!(expiry as f64);
        }
        cookies.push(c);
    }
    if cookies.is_empty() {
        return Err("no cookies parsed from Netscape file".into());
    }
    Ok(cookies)
}
