/* support.sesi
Sesi Support Local Server
Handles visual dashboard requests and executes pure Sesi model queries offline! */

// Global session store
let sessions = {}

// Load repo documents dynamically once at startup
let docs_list = []
try {
  docs_list = list_dir("docs")
} catch (e) {}

let sesiDocs = ""
let d = 0
while d < len(docs_list) {
  let f_name = docs_list[d]
  let parts = split(f_name, ".")
  let ext = parts[len(parts) - 1]
  
  if ext == "md" {
    let doc_content = ""
    try {
      doc_content = read_file("docs/" + f_name)
    } catch (e2) {}
    sesiDocs = sesiDocs + "\n\n=== DOCUMENT: " + f_name + " ===\n" + doc_content
  }
  d = d + 1
}

let system_context = "You are Sesi Support, the official support bot for the Sesi Programming Language. Below is the official reference documentation and native codebase of Sesi: " + sesiDocs + "\nUse this data to answer the user's question with absolute technical precision. Maintain Sesi's programming rules. Be helpful, highly structured, and technical.\n"

async fn handleRequest(req) {
  print "Received request on path:" req.path "with method:" req.method

  // Handle CORS preflight
  if req.method == "OPTIONS" {
    return {
      "status": 200,
      "headers": {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, OPTIONS",
        "Access-Control-Allow-Headers": "X-Requested-With, Content-Type"
      },
      "body": ""
    }
  }

  // Route API Chat queries
  if req.path == "/chat" {
    let q = ""
    if req.query.q {
      q = req.query.q
    }

    if len(q) == 0 {
      return {
        "status": 400,
        "headers": {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*"
        },
        "body": {
          "error": "Empty query parameter 'q'"
        }
      }
    }

    print "[SERVER] Active query logged: '" q "'"

    // 1. Get or initialize session history
    let sessionId = "default"
    if req.query.sessionId {
      sessionId = req.query.sessionId
    }

    let history = ""
    if sessions[sessionId] {
      history = sessions[sessionId]
    } else {
      history = system_context
    }

    let prompt_context = history + "\nUser: " + q + "\n"

    print "[SERVER] Starting native Sesi Support Bot..."
    let response_content = "Sorry, no response could be generated."
    let failed = false
    try {
      response_content = model("gemini-3.1-flash-lite") {temperature: 0.3, max_tokens: 2048} {prompt_context}
    } catch (e) {
      print "[SERVER ERROR] Sesi model call failed:" e
      failed = true
    }

    if failed {
      return {
        "status": 500,
        "headers": {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*"
        },
        "body": {
          "error": "Sesi model call failed"
        }
      }
    }

    // Update session history with assistant's turn
    sessions[sessionId] = prompt_context + "Assistant: " + response_content + "\n"

    print "[SERVER] Response successfully sent."

    return {
      "status": 200,
      "headers": {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, OPTIONS",
        "Access-Control-Allow-Headers": "X-Requested-With, Content-Type"
      },
      "body": {
        "response": response_content
      }
    }
  }

  // Fallback to serving static files (for index.html dashboard!)
  let body = ""
  let contentType = "text/html"
  let status = 200

  if req.path == "/" {
    try {
      body = read_file("chatbot/index.html")
    } catch (e) {
      status = 404
      body = "File not found"
    }
  } else if req.path == "/index.html" {
    try {
      body = read_file("chatbot/index.html")
    } catch (e) {
      status = 404
      body = "File not found"
    }
  } else {
    // Dynamic file serving
    let filename = req.path
    let parts = split(filename, "/")
    if len(parts) > 1 {
      filename = parts[len(parts) - 1]
    }

    let read_success = false

    try {
      body = read_file("chatbot/" + filename)
      read_success = true
    } catch (e) {
      try {
        body = read_file(filename)
        read_success = true
      } catch (e2) {}
    }

    if read_success {
      let ext_parts = split(filename, ".")
      let ext = ext_parts[len(ext_parts) - 1]
      if ext == "html" { contentType = "text/html" }
      if ext == "js" { contentType = "application/javascript" }
      if ext == "css" { contentType = "text/css" }
      if ext == "ico" { contentType = "image/x-icon" }
    } else {
      status = 404
      body = "File not found"
    }
  }

  return {
    "status": status,
    "headers": {
      "Content-Type": contentType,
      "Access-Control-Allow-Origin": "*"
    },
    "body": body
  }
}

// Start HTTP server on Port 8000
let port = 8000
print "=================================================="
print "[STATUS] Sesi Support Online!"
print "[URL] Serving at: http://localhost:8000/index.html"
print "=================================================="

let server = listen(port, handleRequest)
