// Nexus API Client — NVIDIA LLM Interface
// Handles API calls, response parsing, and message building.
// Aislinn McCubbins, April 2026

fn json_escape(s: String) -> String {
    let result = s
    result = str_replace(result, "\\", "\\\\")
    result = str_replace(result, "\"", "\\\"")
    result = str_replace(result, "\n", "\\n")
    result = str_replace(result, "\t", "\\t")
    return result
}

fn nexus_build_messages(system_prompt: String, history: Array, user_msg: String) -> String {
    // Build JSON messages array manually
    // history is alternating: [user1, assistant1, user2, assistant2, ...]
    let json = "["

    // System message
    json = json + "\{\"role\":\"system\",\"content\":\"" + json_escape(system_prompt) + "\"\}"

    // History
    let i = 0
    while i < array_len(history) {
        let role = "user"
        if i % 2 == 1 {
            role = "assistant"
        }
        let msg = array_get(history, i)
        json = json + ",\{\"role\":\"" + role + "\",\"content\":\"" + json_escape(msg) + "\"\}"
        i = i + 1
    }

    // Current user message
    json = json + ",\{\"role\":\"user\",\"content\":\"" + json_escape(user_msg) + "\"\}"
    json = json + "]"

    return json
}

fn nexus_api_call(model: String, messages_json: String, api_key: String, max_tokens: Int, temperature: Float) -> String {
    let url = "https://integrate.api.nvidia.com/v1/chat/completions"

    let body = "\{\"model\":\"" + model + "\","
    body = body + "\"messages\":" + messages_json + ","
    body = body + "\"max_tokens\":" + int_to_str(max_tokens) + ","
    body = body + "\"temperature\":0.7\}"

    let auth_header = "Authorization: Bearer " + api_key
    let content_header = "Content-Type: application/json"

    let result = http_post(url, body, auth_header, content_header)
    return result
}

fn nexus_parse_response(raw: String) -> String {
    // Extract content from: {"choices":[{"message":{"content":"THE RESPONSE"}}]}
    // Find "content":" and extract the value

    if starts_with(raw, "error:") {
        return raw
    }

    let marker = "\"content\":\""
    let pos = str_find(raw, marker)
    if pos < 0 {
        // Try alternate: "content": " (with space)
        let marker2 = "\"content\": \""
        pos = str_find(raw, marker2)
        if pos < 0 {
            return "error: could not find content in response"
        }
        pos = pos + str_len(marker2)
    } else {
        pos = pos + str_len(marker)
    }

    // Scan forward to find the closing unescaped quote
    let result = ""
    let i = pos
    let len = str_len(raw)
    while i < len {
        let ch = str_char_at(raw, i)
        if str_eq(ch, "\\") {
            // Escaped character — take next char as-is
            if i + 1 < len {
                let next = str_char_at(raw, i + 1)
                if str_eq(next, "n") {
                    result = result + "\n"
                } else {
                    if str_eq(next, "t") {
                        result = result + "\t"
                    } else {
                        if str_eq(next, "\"") {
                            result = result + "\""
                        } else {
                            if str_eq(next, "\\") {
                                result = result + "\\"
                            } else {
                                result = result + next
                            }
                        }
                    }
                }
                i = i + 2
            } else {
                i = i + 1
            }
        } else {
            if str_eq(ch, "\"") {
                // End of content string
                return result
            } else {
                result = result + ch
                i = i + 1
            }
        }
    }

    return result
}
