# Markus Maiwald (Architect) | Voxis Forge (AI)
# Scribe: The Sovereign Editor
# A modal line editor for the Sovereign Userland.

import std

var scribe_buffer: seq[string] = @[]
var scribe_filename: string = ""

proc scribe_save() =
  # 1. Create content string
  var content = ""
  for line in scribe_buffer:
    content.add(line)
    content.add('\n')

  # 2. Write to Disk (Using SFS)
  print("[Scribe] Saving '" & scribe_filename & "'...")
  nexus_file_write(scribe_filename, content)

proc start_editor*(filename: string) =
  scribe_filename = filename
  scribe_buffer = @[]

  print("Scribe v1.0. Editing: " & filename)
  if filename == "matrix.conf":
    # Try autoload?
    print("(New File)")

  while true:
    var line = ""
    print_raw(": ")
    if not my_readline(line): break

    if line == ".":
      # Command Mode
      while true:
        var cmd = ""
        print_raw("(cmd) ")
        if not my_readline(cmd): break

        if cmd == "w":
          scribe_save()
          print("Saved.")
          break # Back to prompt or stay? Ed stays in command mode?
          # Ed uses '.' to toggle? No, '.' ends insert.
          # Scribe: '.' enters Command Menu single-shot.
        elif cmd == "p":
          var i = 1
          for l in scribe_buffer:
            print_int(i); print_raw(" "); print(l)
            i += 1
          break
        elif cmd == "q":
          return
        elif cmd == "i":
          print("(Insert Mode)")
          break
        else:
          print("Unknown command. w=save, p=print, q=quit, i=insert")
    else:
      # Append
      scribe_buffer.add(line)
