/*
    Any information here, will be shown in the description of your soul.
    [template]
*/

// CODE EXAMPLES

// your content for <citizen_name>.moon domain
pub async fn moon_domain_resolver() {
    // get nickname of domain resolver at the momemnt
    let nickname =  cyb::context.user.nickname;

    let rng = rand::WyRand::new();
    let rand_int = rng.int_range(0, 999999);

    return content_result(`Hello, ${nickname}, your lucky number is ${rand_int} 🎉`);

    // substitute with some CID (ipfs hosted app in this case)
    // return cid_result("QmcqikiVZJLmum6QRDH7kmLSUuvoPvNiDnCKY4A5nuRw17")
}

// Extend particle page with custom UI elements
pub async fn ask_companion(cid, content_type, content) {
    // plain text item
    let links = [meta_text("similar: ")];
    let rows = [links];

    // search closest 5 particles using local data from the brain
    let similar_results = cyb::search_by_embedding(content, 5).await;


    for v in similar_results {
        // link item
        links.push(meta_link(`/oracle/ask/${v.cid}`, v.text));
    }

    if links.len() == 1 {
        links = [meta_text("no similar particles found")];
    }

	let secrets = cyb::context.secrets;
    if let Some(api_key) = secrets.get("open_ai_key") {
        let messages = [
            #{
                "role": "system",
                "content": "You should give description or summary of any content. aswer should not exceed 32 words"
            },
            #{
                "role": "user",
                "content": content
            }
        ];

        let inference = cyb::open_ai_completions(messages, api_key, #{"model": "gpt-3.5-turbo"}).await;
        rows.push([meta_text(`inference: ${inference}`)]);
    }

    return content_result(rows)
}

// Transform content of the particle
pub async fn personal_processor(cid, content_type, content) {

    // skip any non-text content
    if content_type != "text" {
        return pass()
    }

    // <citizen_name>.moon domain resolver
    if content.ends_with(".moon") {
        let items = content.split(".").collect::<Vec>();

        let username = items[0];
        let ext = items[1];

        if username.len() <= 14 && ext == "moon" {

            // get passport data by username
            let passport = cyb::get_passport_by_nickname(username).await;

            // particle - CID of soul script
            let particle_cid = passport["extension"]["particle"];

            cyb::log(`Resolve ${username} domain from passport particle '${particle_cid}'`);

            // resolve content(script) by cid
            // evaluate 'moon_domain_resolver' from that
            let result = cyb::eval_script_from_ipfs(particle_cid, "moon_domain_resolver", []).await;

            return result
        }
    }

    // example of content exclusion from the search results
    let buzz_word = "пиздопроебанное хуеплетство";

    if content.contains(buzz_word) {
        cyb::log(`Hide ${cid} item because of '${buzz_word}' in the content`);
        return hide()
    }


    // example of content modification
    // replaces cyber with cyber❤
    let highlight_text = "cyber ";
    let highlight_with = "❤ ";

    if content.contains(highlight_text) {
        cyb::log(`Update ${cid} content, highlight ${highlight_text}${highlight_with}`);
        return content_result(content.replace(highlight_text, `${highlight_text}${highlight_with}`))
    }

    // replace <token_name>@NOW (ex. bitcoin@NOW) with actual price in usdt
    // using external api call
    if content.contains("@NOW") {
        let left_part = content.split("@NOW").next().unwrap();
        let token_name = left_part.split(" ").rev().next().unwrap();
        let vs_currency = "usd";

        // external url call
        let json =  http::get(`https://api.coingecko.com/api/v3/simple/price?ids=${token_name}&vs_currencies=${vs_currency}`).await?.json().await?;
        return content_result(content.replace(`${token_name}@NOW`, `Current ${token_name} price is ${json[token_name][vs_currency]} ${vs_currency}`))
    }

    // anything else
	content = content.replace("хуй", "🌽").replace("хуя", "🌽").replace("хуе", "🌽");

    content_result(content)
}

Neighbours