/*  Archome AI — 3ds Max render script
    Kullanim: Scripting (veya MAXScript) > Run Script... > bu dosyayi sec.
    Ilk calistirmada API anahtarini sorar (archome.ai > Settings > API),
    sonra: viewport'u yakalar -> /api/v1/render'a yollar -> render'i tarayicida acar.
    Anahtar kaydedilir; sonraki calistirmalarda tekrar sormaz. */
(
  local apiUrl  = "https://archome.ai/api/v1/render"
  local iniFile = (getDir #plugcfg) + "\\archome_ai.ini"

  fn askString title default_ = (
    dotnet.loadAssembly "Microsoft.VisualBasic"
    (dotNetClass "Microsoft.VisualBasic.Interaction").InputBox title "Archome AI" default_ -1 -1
  )

  -- Eski .NET varsayilani HTTPS'i (TLS 1.2) kirabilir -> acikca ayarla
  try (
    (dotNetClass "System.Net.ServicePointManager").SecurityProtocol = \
      (dotNetClass "System.Net.SecurityProtocolType").Tls12
  ) catch ()

  -- API anahtari (INI'de saklanir)
  local key = getINISetting iniFile "Archome" "ApiKey"
  if key == "" do (
    key = askString "Paste your Archome API key (archome.ai > Settings > API):" ""
    if key == "" do return false
    setINISetting iniFile "Archome" "ApiKey" key
  )

  -- Stil + mod
  local prompt = askString "Style / prompt:" \
    "modern villa, warm wood and stone, large windows, golden hour, photorealistic"
  local mode = askString "Mode (exterior / interior / sketch_to_render):" "exterior"
  if mode == "" do mode = "exterior"
  prompt = substituteString prompt "\"" "'"   -- JSON guvenligi

  -- Aktif viewport -> PNG
  local tmp = (getDir #temp) + "\\archome_max.png"
  local bmp = gw.getViewportDib()
  bmp.filename = tmp
  save bmp
  close bmp

  -- base64
  local bytes = (dotNetClass "System.IO.File").ReadAllBytes tmp
  local b64   = (dotNetClass "System.Convert").ToBase64String bytes

  -- POST (JSON)
  local body = "{\"image\":\"" + b64 + "\",\"prompt\":\"" + prompt + "\",\"tool\":\"" + mode + "\"}"
  local wc = dotNetObject "System.Net.WebClient"
  wc.Headers.Add "Authorization" ("Bearer " + key)
  wc.Headers.Add "Content-Type" "application/json"
  wc.Encoding = (dotNetClass "System.Text.Encoding").UTF8

  messageBox "Rendering... ~30-60s. Click OK; 3ds Max may freeze while it renders, then the result opens in your browser." title:"Archome AI"

  local resp = ""
  local ok = true
  try ( resp = wc.UploadString apiUrl body )
  catch ( ok = false; messageBox ("Request failed:\n" + (getCurrentException())) title:"Archome AI" )
  if not ok do return false

  -- outputUrl'yi cek
  local rx = dotNetObject "System.Text.RegularExpressions.Regex" "\"outputUrl\":\"([^\"]+)\""
  local m  = rx.Match resp
  if m.Success then (
    local url = substituteString (m.Groups.Item[1].Value) "\\/" "/"
    ShellLaunch url ""
    messageBox "Done! Render opened in your browser." title:"Archome AI"
  ) else (
    messageBox ("No render returned:\n" + resp) title:"Archome AI"
  )
)
