;; =============================================================================
;; Conimo Open Sunsama — Open-Source Daily Planner, Time-Blocking & MCP Server
;; Replicates https://opensunsama.com/ (Board, Tasks, Calendar, Focus, Ideas,
;; Routines, and 24-Tool Model Context Protocol / REST API)
;; =============================================================================

(require "libs/conimo/src/server.coni" :as conimo)
(require "libs/conimo/src/html.coni" :as html)
(require "libs/os/src/io.coni" :as io)
(require "libs/store/src/doc.coni" :as doc)
(require "libs/str/src/str.coni" :as str)
(require "libs/json/src/json.coni" :as json)

;; ── Dynamic Calendar & Date Computation ────────────────────────────────────

(defn leap-year? [y]
  (and (= (mod y 4) 0)
       (or (not= (mod y 100) 0)
           (= (mod y 400) 0))))

(defn days-in-month [y m]
  (cond
    (= m 2) (if (leap-year? y) 29 28)
    (or (= m 4) (= m 6) (= m 9) (= m 11)) 30
    :else 31))

(defn step-day [y m d delta]
  (if (= delta 0)
    {:year y :month m :day d}
    (if (> delta 0)
      (let [dim (days-in-month y m)
            nd (+ d 1)]
        (if (> nd dim)
          (if (= m 12)
            (step-day (+ y 1) 1 1 (- delta 1))
            (step-day y (+ m 1) 1 (- delta 1)))
          (step-day y m nd (- delta 1))))
      (let [nd (- d 1)]
        (if (< nd 1)
          (if (= m 1)
            (step-day (- y 1) 12 31 (+ delta 1))
            (let [pm (- m 1)]
              (step-day y pm (days-in-month y pm) (+ delta 1))))
          (step-day y m nd (+ delta 1)))))))

(def weekday-names ["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"])
(def weekday-shorts ["Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat"])
(def month-shorts ["" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"])

(defn pad2 [n]
  (if (< n 10) (str "0" n) (str n)))

(defn date->days [y m d]
  (let [m-adj (if (<= m 2) (+ m 9) (- m 3))
        y-adj (if (<= m 2) (- y 1) y)
        c (int (/ y-adj 100))
        ya (mod y-adj 100)]
    (+ (* 146097 (int (/ c 4)))
       (* 36524 (mod c 4))
       (* 1461 (int (/ ya 4)))
       (* 365 (mod ya 4))
       (int (/ (+ (* m-adj 153) 2) 5))
       (- d 1))))

(defn parse-iso-date [s]
  (if (and s (= (count (str s)) 10))
    (let [parts (str/split (str s) "-")
          y (sys-try-parse-number (nth parts 0))
          m (sys-try-parse-number (nth parts 1))
          d (sys-try-parse-number (nth parts 2))]
      (if (and y m d)
        {:year (int y) :month (int m) :day (int d)}
        nil))
    nil))

(defn iso-days-diff [from-iso to-iso]
  (let [d1 (parse-iso-date from-iso)
        d2 (parse-iso-date to-iso)]
    (if (and d1 d2)
      (- (date->days (:year d2) (:month d2) (:day d2))
         (date->days (:year d1) (:month d1) (:day d1)))
      0)))

(defn compute-days []
  (let [tp (try (sys-time-parts) (catch _ {:year 2026 :month 11 :day 9 :weekday 1}))
        by (or (:year tp) 2026)
        bm (or (:month tp) 11)
        bd (or (:day tp) 9)
        bw (or (:weekday tp) 1)
        offsets [-1 0 1 2 3 4]]
    (into []
      (map (fn [off]
             (let [dt (step-day by bm bd off)
                   y (:year dt)
                   m (:month dt)
                   d (:day dt)
                   w (mod (+ bw off 70) 7)
                   dname (nth weekday-names w)
                   dshort (nth weekday-shorts w)
                   mshort (nth month-shorts m)
                   month-day (str mshort " " d)
                   short-str (str dshort ", " month-day)
                   iso-date (str y "-" (pad2 m) "-" (pad2 d))
                   label (cond
                           (= off -1) "Yesterday"
                           (= off 0)  "Today"
                           (= off 1)  "Tomorrow"
                           :else short-str)]
               {:offset off
                :date iso-date
                :day-name dname
                :day-short dshort
                :month-day month-day
                :short short-str
                :label label}))
           offsets))))

(defn today-iso-str []
  (let [days (compute-days)
        d0 (first (filter #(= (:offset %) 0) days))]
    (if d0 (:date d0) "2026-11-09")))

;; ── Default Seed Data (Matches Open Sunsama `seed-demo.ts` Alex Rivera) ────

(def default-state
  {:theme "light"
   :color-theme "default" ;; "default" (orange #F97316), "ocean" (#2563EB), "emerald" (#10B981), "violet" (#8B5CF6)
   :anchor-date (today-iso-str)
   :profile {:name "Alex Rivera"
             :email "alex@opensunsama.com"
             :role "Head of Product"
             :timezone "Asia/Tokyo"
             :work-start-hour 8
             :work-end-hour 18
             :api-key "os_live_9f8a7b6c5d4e3f2a1b0c"
             :mcp-url "https://sunsama.coni-lang.org/api/mcp"}

   :days (compute-days)

   ;; Clean workspace: zero pre-populated tasks or time blocks
   :tasks []
   :time-blocks []

   ;; Ideas Boards (Trello-style Someday / Exploring / Ready to build)
   :idea-boards [{:id "ib-product"
                  :name "Product bets"
                  :icon "💡"
                  :color "#F59E0B"
                  :columns [{:id "col-someday"
                             :name "Someday"
                             :ideas [{:id "id-1" :title "Voice capture on mobile" :priority "P2" :estimated-mins 90}
                                     {:id "id-2" :title "Habit streaks for recurring tasks" :priority "P3" :estimated-mins 60}
                                     {:id "id-3" :title "Shared team boards" :priority "P2" :estimated-mins 180}]}
                            {:id "col-exploring"
                             :name "Exploring"
                             :ideas [{:id "id-4" :title "AI weekly review summary" :priority "P1" :estimated-mins 120}
                                     {:id "id-5" :title "Slack message → task capture" :priority "P2" :estimated-mins 90}]}
                            {:id "col-ready"
                             :name "Ready to build"
                             :ideas [{:id "id-6" :title "Auto-schedule P0s into open calendar slots" :priority "P0" :estimated-mins 240}]}]}
                 {:id "ib-growth"
                  :name "Personal growth"
                  :icon "🌱"
                  :color "#10B981"
                  :columns [{:id "col-pg-someday"
                             :name "Someday"
                             :ideas [{:id "id-7" :title "Write about async leadership" :priority "P2" :estimated-mins 60}
                                     {:id "id-8" :title "Learn enough Rust to review PRs" :priority "P3" :estimated-mins 120}
                                     {:id "id-9" :title "Give a talk at a product meetup" :priority "P2" :estimated-mins 90}]}
                            {:id "col-pg-exploring"
                             :name "Exploring"
                             :ideas [{:id "id-10" :title "Deep dive into ConiC native compiler" :priority "P1" :estimated-mins 90}]}
                            {:id "col-pg-ready"
                             :name "Ready to build"
                             :ideas [{:id "id-11" :title "Publish Open Sunsama MCP workflow guide" :priority "P1" :estimated-mins 45}]}]}]

   ;; Recurring Routines & Rituals
   :routines [{:id "rt-morning"
               :title "Morning Planning Ritual"
               :schedule "Daily • 08:30"
               :priority "P1"
               :estimated-mins 15
               :channel "#rituals"
               :streak 14
               :active true
               :description "Review calendar meetings, pull P0/P1 tasks from backlog, and time-block deep work."}
              {:id "rt-standup"
               :title "Daily Engineering Standup & Triage"
               :schedule "Weekdays • 09:00"
               :priority "P2"
               :estimated-mins 15
               :channel "#engineering"
               :streak 22
               :active true
               :description "Sync on blockers, review overnight support escalations, and update sprint board."}
              {:id "rt-inbox"
               :title "Afternoon Inbox Zero & Comms Batch"
               :schedule "Weekdays • 16:00"
               :priority "P3"
               :estimated-mins 25
               :channel "#general"
               :streak 9
               :active true
               :description "Process Linear notifications, Slack threads, and investor/customer emails in one batch."}
              {:id "rt-shutdown"
               :title "Evening Shutdown & Rollover Ritual"
               :schedule "Weekdays • 17:30"
               :priority "P1"
               :estimated-mins 10
               :channel "#rituals"
               :streak 18
               :active true
               :description "Check actual vs estimated focus time, gently roll over unfinished tasks to tomorrow, and close laptop."}]

   ;; Connected Calendar Accounts & MCP Connectors
   :calendars [{:id "cal-gcal" :provider "Google Calendar" :account "alex@circo.so" :color "#3B82F6" :synced true :events-count 14}
               {:id "cal-icloud" :provider "iCloud Calendar" :account "alex.rivera@icloud.com" :color "#10B981" :synced true :events-count 4}
               {:id "cal-outlook" :provider "Outlook 365" :account "alex@enterprise.io" :color "#8B5CF6" :synced false :events-count 0}]

   :mcp-clients [{:id "mcp-claude" :name "Claude (Web & Desktop)" :domain "claude.ai" :verified true :protocol "OAuth 2.1 + PKCE (CIMD)" :status "Connected" :last-used "2 mins ago"}
                 {:id "mcp-chatgpt" :name "ChatGPT Developer Mode" :domain "chatgpt.com" :verified true :protocol "OAuth 2.1 + PKCE (CIMD)" :status "Connected" :last-used "1 hour ago"}
                 {:id "mcp-claude-code" :name "Claude Code CLI" :domain "stdio / HTTP" :verified true :protocol "Streamable HTTP" :status "Connected" :last-used "Just now"}
                 {:id "mcp-cursor" :name "Cursor IDE" :domain "cursor.com" :verified true :protocol "Streamable HTTP" :status "Connected" :last-used "Today"}]

   ;; Recent AI / MCP Activity Log
   :mcp-logs [{:id "log-1"
               :ts "09:12 AM"
               :agent "Claude"
               :tool "get_schedule_for_day"
               :summary "Inspected Thursday schedule (8 tasks, 385m planned across 9 time blocks)."}
              {:id "log-2"
               :ts "09:14 AM"
               :agent "Claude"
               :tool "create_time_block"
               :summary "Blocked 09:30–11:00 for 'Deep work: Q4 roadmap' (P0) and linked task t-roadmap."}
              {:id "log-3"
               :ts "10:05 AM"
               :agent "Claude Code"
               :tool "create_subtask"
               :summary "Added 4 subtasks to 'Finalize Q4 roadmap for leadership review'."}]})

;; ── 24 Annotated MCP Tools Metadata ────────────────────────────────────────

(def mcp-tools-catalog
  [{:name "list_tasks"             :category "Tasks"           :readOnly true  :destructive false :description "List tasks filtered by day offset, priority, or completion status."}
   {:name "get_task"               :category "Tasks"           :readOnly true  :destructive false :description "Get full details, notes, and subtasks for a task by ID."}
   {:name "create_task"            :category "Tasks"           :readOnly false :destructive false :description "Create a new task with title, priority (P0-P3), estimatedMins, and scheduled day."}
   {:name "update_task"            :category "Tasks"           :readOnly false :destructive false :description "Update a task's title, priority, estimate, notes, or channel."}
   {:name "complete_task"          :category "Tasks"           :readOnly false :destructive false :description "Mark a task as completed and record actual focus minutes."}
   {:name "uncomplete_task"        :category "Tasks"           :readOnly false :destructive false :description "Reopen a completed task."}
   {:name "delete_task"            :category "Tasks"           :readOnly false :destructive true  :description "Permanently delete a task and unlink its time blocks."}
   {:name "schedule_task"          :category "Tasks"           :readOnly false :destructive false :description "Move a task to Today (0), Tomorrow (1), another day offset, or Backlog (nil)."}
   {:name "reorder_tasks"          :category "Tasks"           :readOnly false :destructive false :description "Reorder tasks within a day column by priority."}
   {:name "list_time_blocks"       :category "Time blocks"     :readOnly true  :destructive false :description "List calendar time blocks for a day or week range."}
   {:name "get_time_block"         :category "Time blocks"     :readOnly true  :destructive false :description "Get a single time block by ID."}
   {:name "create_time_block"      :category "Time blocks"     :readOnly false :destructive false :description "Create a calendar time block with start/end time, color, and optional linked task."}
   {:name "update_time_block"      :category "Time blocks"     :readOnly false :destructive false :description "Update start/end time or title of a time block."}
   {:name "delete_time_block"      :category "Time blocks"     :readOnly false :destructive true  :description "Delete a time block from the schedule."}
   {:name "link_task_to_time_block" :category "Time blocks"    :readOnly false :destructive false :description "Link an existing task to a calendar time block."}
   {:name "get_schedule_for_day"   :category "Time blocks"     :readOnly true  :destructive false :description "Return combined tasks, time blocks, and workload metrics for a day."}
   {:name "list_calendar_events"   :category "Calendar events" :readOnly true  :destructive false :description "List synced external calendar events (Google, Outlook, iCloud)."}
   {:name "list_subtasks"          :category "Subtasks"        :readOnly true  :destructive false :description "List subtasks for a parent task."}
   {:name "create_subtask"         :category "Subtasks"        :readOnly false :destructive false :description "Add a subtask to a parent task."}
   {:name "toggle_subtask"         :category "Subtasks"        :readOnly false :destructive false :description "Toggle completion state of a subtask."}
   {:name "update_subtask"         :category "Subtasks"        :readOnly false :destructive false :description "Rename a subtask."}
   {:name "delete_subtask"         :category "Subtasks"        :readOnly false :destructive true  :description "Remove a subtask from a task."}
   {:name "get_user_profile"       :category "Profile"         :readOnly true  :destructive false :description "Read user profile, work hours, timezone, and preferences."}
   {:name "update_user_profile"    :category "Profile"         :readOnly false :destructive false :description "Update user profile, theme mode, or working hours."}])

;; ── Persistence Layer ──────────────────────────────────────────────────────

(defn resolve-db-path []
  (cond
    (io/exists? "data/opensunsama.edn") "data/opensunsama.edn"
    (io/exists? "opensunsama/data/opensunsama.edn") "opensunsama/data/opensunsama.edn"
    (io/exists? "opensunsama") "opensunsama/data/opensunsama.edn"
    :else "data/opensunsama.edn"))

(defn sync-state-to-today [st]
  (let [live-days (compute-days)
        today-iso (today-iso-str)
        anchor (:anchor-date st)]
    (cond
      (nil? anchor)
      (assoc st :anchor-date today-iso :days live-days)

      (not= anchor today-iso)
      (let [delta (iso-days-diff anchor today-iso)]
        (if (> delta 0)
          (let [tasks (or (:tasks st) [])
                blocks (or (:time-blocks st) [])
                next-tasks (into []
                             (map (fn [t]
                                    (if (nil? (:day t))
                                      t
                                      (let [nd (- (:day t) delta)]
                                        (if (and (< nd 0) (not (:done t)))
                                          (assoc t :day 0)
                                          (assoc t :day nd)))))
                                  tasks))
                next-blocks (into []
                              (filter #(>= (:day %) -1)
                                (map (fn [b]
                                       (if (nil? (:day b))
                                         b
                                         (assoc b :day (- (:day b) delta))))
                                     blocks)))]
            (assoc st
                   :anchor-date today-iso
                   :days live-days
                   :tasks next-tasks
                   :time-blocks next-blocks))
          (assoc st :anchor-date today-iso :days live-days)))

      :else
      (assoc st :days live-days))))

(defn read-state []
  (let [p (resolve-db-path)]
    (if (io/exists? p)
      (let [loaded (doc/read-edn p default-state)]
        (if (and (map? loaded) (contains? loaded :tasks))
          (let [synced (sync-state-to-today loaded)]
            (when (not= (:anchor-date loaded) (:anchor-date synced))
              (doc/write-edn! p synced))
            synced)
          (let [fresh (sync-state-to-today default-state)]
            (doc/write-edn! p fresh)
            fresh)))
      (let [fresh (sync-state-to-today default-state)]
        (doc/write-edn! p fresh)
        fresh))))

(defn write-state! [st]
  (let [synced (assoc st :days (compute-days) :anchor-date (or (:anchor-date st) (today-iso-str)))]
    (doc/write-edn! (resolve-db-path) synced)
    synced))

;; ── Computed Enrichments ───────────────────────────────────────────────────

(defn enrich-state [st]
  (let [live-days (compute-days)
        tasks (or (:tasks st) [])
        today-tasks (filter #(= (:day %) 0) tasks)
        today-planned-mins (reduce (fn [acc t] (+ acc (or (:estimated-mins t) 0))) 0 today-tasks)
        today-actual-mins (reduce (fn [acc t] (+ acc (or (:actual-mins t) 0))) 0 today-tasks)
        today-done-count (count (filter :done today-tasks))
        today-total-count (count today-tasks)]
    (assoc st
           :days live-days
           :anchor-date (today-iso-str)
           :mcp-tools mcp-tools-catalog
           :metrics {:today-planned-mins today-planned-mins
                     :today-actual-mins today-actual-mins
                     :today-done-count today-done-count
                     :today-total-count today-total-count})))

(defn edn-response [status payload]
  {:status status
   :headers {"Content-Type" "application/edn"
             "Cache-Control" "no-cache"}
   :body (pr-str payload)})

(defn json-response [status payload]
  {:status status
   :headers {"Content-Type" "application/json"
             "Access-Control-Allow-Origin" "*"
             "Cache-Control" "no-cache"}
   :body (json/stringify payload)})

(defn parse-body [req]
  (if (:body req)
    (try (read-string (:body req)) (catch _ nil))
    nil))

(defn parse-json-or-edn [req]
  (let [b (:body req)]
    (if (and b (not= (str/trim (str b)) ""))
      (let [trimmed (str/trim (str b))]
        (if (str/starts-with? trimmed "{")
          (or (try (json/parse trimmed) (catch _ nil))
              (try (read-string trimmed) (catch _ nil)))
          (try (read-string trimmed) (catch _ nil))))
      nil)))

(defn append-mcp-log [st agent tool summary]
  (let [logs (or (:mcp-logs st) [])
        entry {:id (str "log-" (sys-time-now))
               :ts "Just now"
               :agent (or agent "AI Agent")
               :tool tool
               :summary summary}]
    (assoc st :mcp-logs (into [entry] (take 19 logs)))))

;; ── API Handlers ───────────────────────────────────────────────────────────

(defn handle-get-state [_]
  (let [st (enrich-state (read-state))]
    (edn-response 200 {:ok true :state st})))

(defn handle-theme [req]
  (let [body (parse-body req)
        st (read-state)
        cur (or (:theme st) "light")
        next-theme (or (:theme body) (if (= cur "dark") "light" "dark"))
        next-color (or (:color-theme body) (:color-theme st) "default")
        updated (write-state! (assoc st :theme next-theme :color-theme next-color))]
    (edn-response 200 {:ok true :state (enrich-state updated)})))

(defn handle-profile-update [req]
  (let [body (parse-body req)
        st (read-state)
        prof (or (:profile st) {})
        next-prof (merge prof
                         (if (:name body) {:name (str/trim (str (:name body)))} {})
                         (if (:role body) {:role (str/trim (str (:role body)))} {})
                         (if (:timezone body) {:timezone (str/trim (str (:timezone body)))} {})
                         (if (:work-start-hour body) {:work-start-hour (:work-start-hour body)} {})
                         (if (:work-end-hour body) {:work-end-hour (:work-end-hour body)} {}))
        updated (write-state! (assoc st :profile next-prof))]
    (edn-response 200 {:ok true :state (enrich-state updated)})))

(defn normalize-tag [raw]
  (let [s (str/trim (str (or raw "")))]
    (cond
      (= s "") nil
      (str/starts-with? s "#") s
      :else (str "#" s))))

(defn extract-inline-tag [raw-title explicit-chan]
  (let [words (str/split (str/trim (str raw-title)) " ")
        tag-word (first (filter #(and (> (count %) 1) (str/starts-with? % "#")) words))
        clean-words (filter #(not (and (> (count %) 1) (str/starts-with? % "#"))) words)
        clean-title (str/trim (str/join " " clean-words))
        final-title (if (> (count clean-title) 0) clean-title (str/trim (str raw-title)))
        final-chan (or (normalize-tag explicit-chan) (normalize-tag tag-word))]
    {:title final-title :channel final-chan}))

(defn handle-task-add [req]
  (let [body (parse-body req)
        raw-title (if body (str/trim (str (or (:title body) ""))) "")]
    (if (> (count raw-title) 0)
      (let [st (read-state)
            tasks (or (:tasks st) [])
            parsed (extract-inline-tag raw-title (:channel body))
            title (:title parsed)
            chan (:channel parsed)
            day-val (if (contains? body :day) (:day body) 0)
            est (or (sys-try-parse-number (str (or (:estimated-mins body) 30))) 30)
            prio (or (:priority body) "P2")
            new-task {:id (str "t-" (sys-time-now))
                      :title title
                      :priority prio
                      :estimated-mins est
                      :actual-mins 0
                      :day day-val
                      :channel chan
                      :done false
                      :notes (or (:notes body) "")
                      :subtasks []}
            updated (write-state! (assoc st :tasks (conj tasks new-task)))]
        (edn-response 200 {:ok true :state (enrich-state updated) :task new-task}))
      (edn-response 400 {:ok false :error "Task title is required"}))))

(defn handle-task-toggle [req]
  (let [body (parse-body req)
        tid (if body (:id body) nil)]
    (if tid
      (let [st (read-state)
            tasks (or (:tasks st) [])
            next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) tid)
                                  (let [nd (not (:done t))
                                        act (if (and nd (= (or (:actual-mins t) 0) 0))
                                              (or (:estimated-mins t) 15)
                                              (or (:actual-mins t) 0))]
                                    (assoc t :done nd :actual-mins act))
                                  t))
                              tasks))
            updated (write-state! (assoc st :tasks next-tasks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing task id"}))))

(defn handle-task-update [req]
  (let [body (parse-body req)
        tid (if body (:id body) nil)]
    (if tid
      (let [st (read-state)
            tasks (or (:tasks st) [])
            parsed-title (if (:title body)
                           (extract-inline-tag (:title body) nil)
                           nil)
            next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) tid)
                                  (merge t
                                         (if parsed-title {:title (:title parsed-title)} {})
                                         (if (and parsed-title (:channel parsed-title) (not (contains? body :channel)))
                                           {:channel (:channel parsed-title)}
                                           {})
                                         (if (:priority body) {:priority (:priority body)} {})
                                         (if (:estimated-mins body) {:estimated-mins (or (sys-try-parse-number (str (:estimated-mins body))) (:estimated-mins t))} {})
                                         (if (:actual-mins body) {:actual-mins (or (sys-try-parse-number (str (:actual-mins body))) (:actual-mins t))} {})
                                         (if (:notes body) {:notes (str (:notes body))} {})
                                         (if (contains? body :channel) {:channel (normalize-tag (:channel body))} {})
                                         (if (contains? body :day) {:day (:day body)} {}))
                                  t))
                              tasks))
            updated (write-state! (assoc st :tasks next-tasks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing task id"}))))

(defn handle-task-schedule [req]
  (let [body (parse-body req)
        tid (if body (:id body) nil)]
    (if tid
      (let [st (read-state)
            target-day (:day body)
            tasks (or (:tasks st) [])
            next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) tid)
                                  (assoc t :day target-day)
                                  t))
                              tasks))
            updated (write-state! (assoc st :tasks next-tasks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing task id"}))))

(defn handle-task-delete [req]
  (let [body (parse-body req)
        tid (if body (:id body) nil)]
    (if tid
      (let [st (read-state)
            tasks (or (:tasks st) [])
            blocks (or (:time-blocks st) [])
            next-tasks (into [] (filter #(not= (:id %) tid) tasks))
            next-blocks (into [] (map #(if (= (:task-id %) tid) (assoc % :task-id nil) %) blocks))
            updated (write-state! (assoc st :tasks next-tasks :time-blocks next-blocks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing task id"}))))

(defn handle-task-clear [_]
  (let [st (read-state)
        updated (write-state! (assoc st :tasks [] :time-blocks []))]
    (edn-response 200 {:ok true :state (enrich-state updated)})))

(defn handle-task-rollover [_]
  (let [st (read-state)
        tasks (or (:tasks st) [])
        ;; Move unfinished tasks from Yesterday (-1) to Today (0), or from Today (0) to Tomorrow (1)
        next-tasks (into []
                     (map (fn [t]
                            (cond
                              (and (= (:day t) -1) (not (:done t))) (assoc t :day 0)
                              (and (= (:day t) 0) (not (:done t)) (or (= (:priority t) "P2") (= (:priority t) "P3"))) (assoc t :day 1)
                              :else t))
                          tasks))
        st-logged (append-mcp-log (assoc st :tasks next-tasks) "Sunsama Rollover" "schedule_task" "Rolled over unfinished P2/P3 tasks to tomorrow.")
        updated (write-state! st-logged)]
    (edn-response 200 {:ok true :state (enrich-state updated)})))

(defn handle-task-focus-log [req]
  (let [body (parse-body req)
        tid (if body (:id body) nil)
        add-mins (or (sys-try-parse-number (str (or (:mins body) 15))) 15)
        mark-done? (:done body)]
    (if tid
      (let [st (read-state)
            tasks (or (:tasks st) [])
            next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) tid)
                                  (assoc t
                                         :actual-mins (+ (or (:actual-mins t) 0) add-mins)
                                         :done (if (nil? mark-done?) (:done t) mark-done?))
                                  t))
                              tasks))
            updated (write-state! (assoc st :tasks next-tasks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing task id"}))))

;; ── Subtask Handlers ───────────────────────────────────────────────────────

(defn handle-subtask-add [req]
  (let [body (parse-body req)
        tid (if body (:task-id body) nil)
        title (if body (str/trim (str (or (:title body) ""))) "")]
    (if (and tid (> (count title) 0))
      (let [st (read-state)
            tasks (or (:tasks st) [])
            new-st {:id (str "st-" (sys-time-now)) :title title :done false}
            next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) tid)
                                  (assoc t :subtasks (conj (or (:subtasks t) []) new-st))
                                  t))
                              tasks))
            updated (write-state! (assoc st :tasks next-tasks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing task-id or subtask title"}))))

(defn handle-subtask-toggle [req]
  (let [body (parse-body req)
        tid (if body (:task-id body) nil)
        sid (if body (:subtask-id body) nil)]
    (if (and tid sid)
      (let [st (read-state)
            tasks (or (:tasks st) [])
            next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) tid)
                                  (let [subs (or (:subtasks t) [])
                                        next-subs (into []
                                                    (map (fn [s]
                                                           (if (= (:id s) sid)
                                                             (assoc s :done (not (:done s)))
                                                             s))
                                                         subs))]
                                    (assoc t :subtasks next-subs))
                                  t))
                              tasks))
            updated (write-state! (assoc st :tasks next-tasks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing task-id or subtask-id"}))))

(defn handle-subtask-delete [req]
  (let [body (parse-body req)
        tid (if body (:task-id body) nil)
        sid (if body (:subtask-id body) nil)]
    (if (and tid sid)
      (let [st (read-state)
            tasks (or (:tasks st) [])
            next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) tid)
                                  (assoc t :subtasks (into [] (filter #(not= (:id %) sid) (or (:subtasks t) []))))
                                  t))
                              tasks))
            updated (write-state! (assoc st :tasks next-tasks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing task-id or subtask-id"}))))

;; ── Time Block Handlers ────────────────────────────────────────────────────

(defn priority-color [prio]
  (cond
    (= prio "P0") "#EF4444"
    (= prio "P1") "#F59E0B"
    (= prio "P2") "#3B82F6"
    :else "#8B5CF6"))

(defn handle-block-add [req]
  (let [body (parse-body req)
        st (read-state)
        tasks (or (:tasks st) [])
        blocks (or (:time-blocks st) [])
        tid (:task-id body)
        linked-task (if tid (first (filter #(= (:id %) tid) tasks)) nil)
        title (str/trim (str (or (:title body) (if linked-task (:title linked-task) ""))))
        day-val (if (contains? body :day) (:day body) (if linked-task (or (:day linked-task) 0) 0))
        start-time (or (:start body) "11:00")
        end-time (or (:end body) "12:00")
        color (or (:color body) (if linked-task (priority-color (:priority linked-task)) "#F97316"))]
    (if (> (count title) 0)
      (let [new-block {:id (str "tb-" (sys-time-now))
                       :day day-val
                       :start start-time
                       :end end-time
                       :title title
                       :color color
                       :source (or (:source body) "block")
                       :task-id tid}
            ;; Also ensure linked task is scheduled on that day if it was in backlog
            next-tasks (if tid
                         (into [] (map #(if (and (= (:id %) tid) (nil? (:day %))) (assoc % :day day-val) %) tasks))
                         tasks)
            updated (write-state! (assoc st :time-blocks (conj blocks new-block) :tasks next-tasks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Time block title is required"}))))

(defn handle-block-update [req]
  (let [body (parse-body req)
        bid (if body (:id body) nil)]
    (if bid
      (let [st (read-state)
            blocks (or (:time-blocks st) [])
            next-blocks (into []
                          (map (fn [b]
                                 (if (= (:id b) bid)
                                   (merge b
                                          (if (:start body) {:start (str (:start body))} {})
                                          (if (:end body) {:end (str (:end body))} {})
                                          (if (:title body) {:title (str (:title body))} {})
                                          (if (contains? body :day) {:day (:day body)} {}))
                                   b))
                               blocks))
            updated (write-state! (assoc st :time-blocks next-blocks))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing block id"}))))

(defn handle-block-delete [req]
  (let [body (parse-body req)
        bid (if body (:id body) nil)]
    (if bid
      (let [st (read-state)
            blocks (or (:time-blocks st) [])
            updated (write-state! (assoc st :time-blocks (into [] (filter #(not= (:id %) bid) blocks))))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing block id"}))))

;; ── Ideas Board Handlers ───────────────────────────────────────────────────

(defn handle-idea-add [req]
  (let [body (parse-body req)
        board-id (or (:board-id body) "ib-product")
        col-id (or (:column-id body) "col-someday")
        title (if body (str/trim (str (or (:title body) ""))) "")]
    (if (> (count title) 0)
      (let [st (read-state)
            boards (or (:idea-boards st) [])
            new-idea {:id (str "id-" (sys-time-now))
                      :title title
                      :priority (or (:priority body) "P2")
                      :estimated-mins (or (sys-try-parse-number (str (or (:estimated-mins body) 45))) 45)}
            next-boards (into []
                          (map (fn [b]
                                 (if (= (:id b) board-id)
                                   (let [cols (or (:columns b) [])
                                         next-cols (into []
                                                     (map (fn [c]
                                                            (if (= (:id c) col-id)
                                                              (assoc c :ideas (conj (or (:ideas c) []) new-idea))
                                                              c))
                                                          cols))]
                                     (assoc b :columns next-cols))
                                   b))
                               boards))
            updated (write-state! (assoc st :idea-boards next-boards))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Idea title is required"}))))

(defn handle-idea-promote [req]
  (let [body (parse-body req)
        idea-id (if body (:id body) nil)
        target-day (if (contains? body :day) (:day body) 0)]
    (if idea-id
      (let [st (read-state)
            boards (or (:idea-boards st) [])
            ;; Find the idea across all boards/columns
            found-atom (atom nil)
            next-boards (into []
                          (map (fn [b]
                                 (let [next-cols (into []
                                                   (map (fn [c]
                                                          (let [ideas (or (:ideas c) [])
                                                                match (first (filter #(= (:id %) idea-id) ideas))]
                                                            (when match (reset! found-atom match))
                                                            (assoc c :ideas (into [] (filter #(not= (:id %) idea-id) ideas)))))
                                                        (or (:columns b) [])))]
                                   (assoc b :columns next-cols)))
                               boards))
            idea (deref found-atom)]
        (if idea
          (let [tasks (or (:tasks st) [])
                new-task {:id (str "t-idea-" (sys-time-now))
                          :title (:title idea)
                          :priority (or (:priority idea) "P2")
                          :estimated-mins (or (:estimated-mins idea) 45)
                          :actual-mins 0
                          :day target-day
                          :channel "#ideas"
                          :done false
                          :notes "Promoted from Ideas board."
                          :subtasks []}
                updated (write-state! (assoc st :idea-boards next-boards :tasks (conj tasks new-task)))]
            (edn-response 200 {:ok true :state (enrich-state updated)}))
          (edn-response 404 {:ok false :error "Idea not found"})))
      (edn-response 400 {:ok false :error "Missing idea id"}))))

(defn handle-idea-delete [req]
  (let [body (parse-body req)
        idea-id (if body (:id body) nil)]
    (if idea-id
      (let [st (read-state)
            boards (or (:idea-boards st) [])
            next-boards (into []
                          (map (fn [b]
                                 (assoc b :columns
                                        (into []
                                          (map (fn [c]
                                                 (assoc c :ideas (into [] (filter #(not= (:id %) idea-id) (or (:ideas c) [])))))
                                               (or (:columns b) [])))))
                               boards))
            updated (write-state! (assoc st :idea-boards next-boards))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Missing idea id"}))))

;; ── Routines Handlers ──────────────────────────────────────────────────────

(defn handle-routine-run [req]
  (let [body (parse-body req)
        rid (if body (:id body) nil)]
    (if rid
      (let [st (read-state)
            routines (or (:routines st) [])
            rt (first (filter #(= (:id %) rid) routines))]
        (if rt
          (let [tasks (or (:tasks st) [])
                new-task {:id (str "t-rt-" (sys-time-now))
                          :title (:title rt)
                          :priority (or (:priority rt) "P2")
                          :estimated-mins (or (:estimated-mins rt) 15)
                          :actual-mins 0
                          :day 0
                          :channel (or (:channel rt) "#rituals")
                          :done false
                          :notes (or (:description rt) "")
                          :subtasks []}
                next-routines (into [] (map #(if (= (:id %) rid) (assoc % :streak (+ (or (:streak %) 0) 1)) %) routines))
                updated (write-state! (assoc st :tasks (conj tasks new-task) :routines next-routines))]
            (edn-response 200 {:ok true :state (enrich-state updated)}))
          (edn-response 404 {:ok false :error "Routine not found"})))
      (edn-response 400 {:ok false :error "Missing routine id"}))))

(defn handle-routine-add [req]
  (let [body (parse-body req)
        title (if body (str/trim (str (or (:title body) ""))) "")]
    (if (> (count title) 0)
      (let [st (read-state)
            routines (or (:routines st) [])
            new-rt {:id (str "rt-" (sys-time-now))
                    :title title
                    :schedule (or (:schedule body) "Weekdays • 09:00")
                    :priority (or (:priority body) "P2")
                    :estimated-mins (or (sys-try-parse-number (str (or (:estimated-mins body) 15))) 15)
                    :channel (or (:channel body) "#rituals")
                    :streak 1
                    :active true
                    :description (or (:description body) "Recurring daily planning routine.")}
            updated (write-state! (assoc st :routines (conj routines new-rt)))]
        (edn-response 200 {:ok true :state (enrich-state updated)}))
      (edn-response 400 {:ok false :error "Routine title required"}))))

;; ── AI Assistant & 24-Tool MCP Execution Engine ────────────────────────────

(defn execute-mcp-tool! [tool-name args agent-name]
  (let [st (read-state)
        tasks (or (:tasks st) [])
        blocks (or (:time-blocks st) [])]
    (cond
      (= tool-name "list_tasks")
      (let [day-filter (if (contains? args :day) (:day args) nil)
            prio-filter (:priority args)
            filtered (filter (fn [t]
                               (and (if (contains? args :day) (= (:day t) day-filter) true)
                                    (if prio-filter (= (:priority t) prio-filter) true)))
                             tasks)
            st2 (write-state! (append-mcp-log st agent-name "list_tasks" (str "Listed " (count filtered) " tasks.")))]
        {:ok true :tool tool-name :result (into [] filtered) :state (enrich-state st2)})

      (= tool-name "get_schedule_for_day")
      (let [d (or (:day args) 0)
            day-tasks (into [] (filter #(= (:day %) d) tasks))
            day-blocks (into [] (filter #(= (:day %) d) blocks))
            total-mins (reduce (fn [acc t] (+ acc (or (:estimated-mins t) 0))) 0 day-tasks)
            st2 (write-state! (append-mcp-log st agent-name "get_schedule_for_day" (str "Read Day " d " schedule (" (count day-tasks) " tasks, " total-mins "m planned).")))]
        {:ok true
         :tool tool-name
         :result {:day d :tasks day-tasks :timeBlocks day-blocks :plannedMins total-mins}
         :state (enrich-state st2)})

      (= tool-name "create_task")
      (let [title (str/trim (str (or (:title args) "AI Planned Task")))
            prio (or (:priority args) "P1")
            mins (or (sys-try-parse-number (str (or (:estimatedMins args) (:estimated-mins args) 45))) 45)
            d (if (contains? args :day) (:day args) 0)
            new-t {:id (str "t-mcp-" (sys-time-now))
                   :title title
                   :priority prio
                   :estimated-mins mins
                   :actual-mins 0
                   :day d
                   :channel (or (:channel args) "#ai-planned")
                   :done false
                   :notes (or (:notes args) "Created via Open Sunsama MCP connector.")
                   :subtasks []}
            st2 ( -> st
                     (assoc :tasks (conj tasks new-t))
                     (append-mcp-log agent-name "create_task" (str "Created " prio " task '" title "' (" mins "m)."))
                     (write-state!))]
        {:ok true :tool tool-name :result new-t :state (enrich-state st2)})

      (= tool-name "create_time_block")
      (let [title (str/trim (str (or (:title args) "Deep Work Block")))
            d (or (:day args) 0)
            start-t (or (:startTime args) (:start args) "09:30")
            end-t (or (:endTime args) (:end args) "11:00")
            tid (or (:taskId args) (:task-id args))
            new-b {:id (str "tb-mcp-" (sys-time-now))
                   :day d
                   :start start-t
                   :end end-t
                   :title title
                   :color (or (:color args) "#EF4444")
                   :source "block"
                   :task-id tid}
            st2 (-> st
                    (assoc :time-blocks (conj blocks new-b))
                    (append-mcp-log agent-name "create_time_block" (str "Blocked " start-t "–" end-t " for '" title "'."))
                    (write-state!))]
        {:ok true :tool tool-name :result new-b :state (enrich-state st2)})

      (= tool-name "schedule_task")
      (let [tid (or (:taskId args) (:id args))
            target-day (if (contains? args :day) (:day args) 1)
            next-tasks (into [] (map #(if (= (:id %) tid) (assoc % :day target-day) %) tasks))
            st2 (-> st
                    (assoc :tasks next-tasks)
                    (append-mcp-log agent-name "schedule_task" (str "Moved task " tid " to day offset " target-day "."))
                    (write-state!))]
        {:ok true :tool tool-name :result {:id tid :day target-day} :state (enrich-state st2)})

      (= tool-name "complete_task")
      (let [tid (or (:taskId args) (:id args))
            next-tasks (into [] (map #(if (= (:id %) tid) (assoc % :done true :actual-mins (or (:estimated-mins %) 30)) %) tasks))
            st2 (-> st
                    (assoc :tasks next-tasks)
                    (append-mcp-log agent-name "complete_task" (str "Marked task " tid " complete."))
                    (write-state!))]
        {:ok true :tool tool-name :result {:id tid :done true} :state (enrich-state st2)})

      (= tool-name "create_subtask")
      (let [tid (or (:taskId args) (:task-id args) "t-board-deck")
            stitle (str/trim (str (or (:title args) "New subtask")))
            new-sub {:id (str "st-mcp-" (sys-time-now)) :title stitle :done false}
            next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) tid)
                                  (assoc t :subtasks (conj (or (:subtasks t) []) new-sub))
                                  t))
                              tasks))
            st2 (-> st
                    (assoc :tasks next-tasks)
                    (append-mcp-log agent-name "create_subtask" (str "Added subtask '" stitle "' to " tid "."))
                    (write-state!))]
        {:ok true :tool tool-name :result new-sub :state (enrich-state st2)})

      (= tool-name "list_calendar_events")
      (let [gcal-blocks (into [] (filter #(= (:source %) "gcal") blocks))
            st2 (write-state! (append-mcp-log st agent-name "list_calendar_events" (str "Fetched " (count gcal-blocks) " synced calendar events.")))]
        {:ok true :tool tool-name :result gcal-blocks :state (enrich-state st2)})

      (= tool-name "get_user_profile")
      (let [st2 (write-state! (append-mcp-log st agent-name "get_user_profile" "Read user profile & work hours."))]
        {:ok true :tool tool-name :result (:profile st2) :state (enrich-state st2)})

      :else
      (let [st2 (write-state! (append-mcp-log st agent-name tool-name (str "Executed MCP tool " tool-name ".")))]
        {:ok true :tool tool-name :result {:status "ok" :tool tool-name} :state (enrich-state st2)}))))

;; Built-in AI Planner Presets (matching Open Sunsama's README prompts!)
;; 1. "triage-today": "What's on my plate today? Move anything that isn't a P0 or P1 to tomorrow."
;; 2. "block-deep-work": "Block 9–11am tomorrow for deep work on the launch plan and link it to that task."
;; 3. "board-subtasks": "Add subtasks to 'Board deck': metrics slide, roadmap slide, asks."
;; 4. "auto-schedule-p0": "Auto-schedule all unscheduled P0/P1 tasks into open calendar slots."

(defn handle-ai-prompt [req]
  (let [body (parse-body req)
        preset (or (:preset body) "triage-today")
        custom-prompt (str/trim (str (or (:prompt body) "")))
        st (read-state)
        tasks (or (:tasks st) [])
        blocks (or (:time-blocks st) [])]
    (cond
      (= preset "triage-today")
      (let [moved-count (count (filter #(and (= (:day %) 0) (not (:done %)) (not= (:priority %) "P0") (not= (:priority %) "P1")) tasks))
            next-tasks (into []
                         (map (fn [t]
                                (if (and (= (:day t) 0) (not (:done t)) (not= (:priority t) "P0") (not= (:priority t) "P1"))
                                  (assoc t :day 1)
                                  t))
                              tasks))
            msg (str "Triaged Today's plate: kept P0/P1 focus tasks and moved " moved-count " P2/P3 tasks to Tomorrow.")
            st2 (-> st
                    (assoc :tasks next-tasks)
                    (append-mcp-log "Claude (MCP)" "schedule_task" msg)
                    (write-state!))]
        (edn-response 200 {:ok true :message msg :state (enrich-state st2)}))

      (= preset "block-deep-work")
      (let [new-task-id (str "t-launch-" (sys-time-now))
            new-task {:id new-task-id
                      :title "Deep work: AI Assistant launch plan"
                      :priority "P0"
                      :estimated-mins 120
                      :actual-mins 0
                      :day 1
                      :channel "#launch"
                      :done false
                      :notes "Created & time-blocked by AI Assistant via MCP."
                      :subtasks [{:id "st-lp1" :title "Finalize launch narrative & demo video" :done false}
                                 {:id "st-lp2" :title "Verify OAuth 2.1 CIMD connector badges" :done false}]}
            new-block {:id (str "tb-launch-" (sys-time-now))
                       :day 1
                       :start "09:00"
                       :end "11:00"
                       :title "Deep work: AI Assistant launch plan"
                       :color "#EF4444"
                       :source "block"
                       :task-id new-task-id}
            msg "Blocked 09:00–11:00 tomorrow for 'Deep work: AI Assistant launch plan' (P0) and linked task."
            st2 (-> st
                    (assoc :tasks (conj tasks new-task)
                           :time-blocks (conj blocks new-block))
                    (append-mcp-log "Claude (MCP)" "create_time_block" msg)
                    (write-state!))]
        (edn-response 200 {:ok true :message msg :state (enrich-state st2)}))

      (= preset "board-subtasks")
      (let [next-tasks (into []
                         (map (fn [t]
                                (if (= (:id t) "t-board-deck")
                                  (assoc t :subtasks
                                         [{:id "st-bd-1" :title "Metrics slide (ARR, NRR, WAU)" :done true}
                                          {:id "st-bd-2" :title "Q4 & 2027 Product Roadmap slide" :done false}
                                          {:id "st-bd-3" :title "Strategic asks & hiring headcount" :done false}
                                          {:id "st-bd-4" :title "Live MCP demo appendix" :done false}])
                                  t))
                              tasks))
            msg "Added 4 structured subtasks to 'Board deck: product section'."
            st2 (-> st
                    (assoc :tasks next-tasks)
                    (append-mcp-log "ChatGPT (MCP)" "create_subtask" msg)
                    (write-state!))]
        (edn-response 200 {:ok true :message msg :state (enrich-state st2)}))

      :else
      ;; Custom natural language prompt -> creates a smart P1 task and time-blocks it
      (let [title (if (> (count custom-prompt) 0) custom-prompt "AI Auto-Scheduled Deep Work")
            tid (str "t-ai-" (sys-time-now))
            new-t {:id tid
                   :title title
                   :priority "P1"
                   :estimated-mins 45
                   :actual-mins 0
                   :day 0
                   :channel "#ai-agent"
                   :done false
                   :notes (str "Scheduled from AI prompt: \"" title "\"")
                   :subtasks []}
            new-b {:id (str "tb-ai-" (sys-time-now))
                   :day 0
                   :start "16:30"
                   :end "17:15"
                   :title title
                   :color "#F97316"
                   :source "block"
                   :task-id tid}
            msg (str "AI Agent scheduled '" title "' onto Today's board and blocked 16:30–17:15.")
            st2 (-> st
                    (assoc :tasks (conj tasks new-t)
                           :time-blocks (conj blocks new-b))
                    (append-mcp-log "Claude Code (MCP)" "create_task" msg)
                    (write-state!))]
        (edn-response 200 {:ok true :message msg :state (enrich-state st2)})))))

(defn handle-mcp-call-edn [req]
  (let [body (parse-body req)
        tool-name (str (or (:tool body) "get_schedule_for_day"))
        args (or (:args body) {})
        agent (or (:agent body) "MCP Playground")
        res (execute-mcp-tool! tool-name args agent)]
    (edn-response 200 res)))

;; JSON-RPC 2.0 Streamable HTTP MCP Endpoint (`POST /api/mcp` and `GET /api/mcp`)
(defn handle-mcp-http [req]
  (if (= (:method req) "GET")
    (json-response 200
      {:protocol "mcp/2025-03-26"
       :serverInfo {:name "open-sunsama-conimo"
                    :version "2.0.0"
                    :description "Open Sunsama AI-Native Daily Planner & Time-Blocking MCP Server"}
       :capabilities {:tools {:listChanged true}}
       :tools mcp-tools-catalog})
    (let [payload (or (parse-json-or-edn req) {})
          rpc-id (or (:id payload) 1)
          method (or (:method payload) "tools/list")
          params (or (:params payload) {})]
      (cond
        (= method "initialize")
        (json-response 200
          {:jsonrpc "2.0"
           :id rpc-id
           :result {:protocolVersion "2025-03-26"
                    :serverInfo {:name "open-sunsama-conimo" :version "2.0.0"}
                    :capabilities {:tools {:listChanged true}}}})

        (= method "tools/list")
        (json-response 200
          {:jsonrpc "2.0"
           :id rpc-id
           :result {:tools mcp-tools-catalog}})

        (= method "tools/call")
        (let [tname (str (or (:name params) "get_schedule_for_day"))
              targs (or (:arguments params) {})
              exec-res (execute-mcp-tool! tname targs "MCP HTTP Client")]
          (json-response 200
            {:jsonrpc "2.0"
             :id rpc-id
             :result {:content [{:type "text"
                                 :text (json/stringify (:result exec-res))}]
                      :isError false}}))

        :else
        (json-response 200
          {:jsonrpc "2.0"
           :id rpc-id
           :result {:tools mcp-tools-catalog}})))))

(defn handle-reset [_]
  (let [updated (write-state! default-state)]
    (edn-response 200 {:ok true :state (enrich-state updated)})))

;; ── API Router ─────────────────────────────────────────────────────────────

(def api-handler
  (conimo/router
    [{:method "GET"  :path "/api/state"          :handler handle-get-state}
     {:method "POST" :path "/api/theme"          :handler handle-theme}
     {:method "POST" :path "/api/profile/update" :handler handle-profile-update}
     {:method "POST" :path "/api/task/add"       :handler handle-task-add}
     {:method "POST" :path "/api/task/toggle"    :handler handle-task-toggle}
     {:method "POST" :path "/api/task/update"    :handler handle-task-update}
     {:method "POST" :path "/api/task/schedule"  :handler handle-task-schedule}
     {:method "POST" :path "/api/task/delete"    :handler handle-task-delete}
     {:method "POST" :path "/api/task/clear"     :handler handle-task-clear}
     {:method "POST" :path "/api/task/rollover"  :handler handle-task-rollover}
     {:method "POST" :path "/api/task/focus"     :handler handle-task-focus-log}
     {:method "POST" :path "/api/subtask/add"    :handler handle-subtask-add}
     {:method "POST" :path "/api/subtask/toggle" :handler handle-subtask-toggle}
     {:method "POST" :path "/api/subtask/delete" :handler handle-subtask-delete}
     {:method "POST" :path "/api/block/add"      :handler handle-block-add}
     {:method "POST" :path "/api/block/update"   :handler handle-block-update}
     {:method "POST" :path "/api/block/delete"   :handler handle-block-delete}
     {:method "POST" :path "/api/idea/add"       :handler handle-idea-add}
     {:method "POST" :path "/api/idea/promote"   :handler handle-idea-promote}
     {:method "POST" :path "/api/idea/delete"    :handler handle-idea-delete}
     {:method "POST" :path "/api/routine/run"    :handler handle-routine-run}
     {:method "POST" :path "/api/routine/add"    :handler handle-routine-add}
     {:method "POST" :path "/api/ai/prompt"      :handler handle-ai-prompt}
     {:method "POST" :path "/api/mcp/call"       :handler handle-mcp-call-edn}
     {:method "GET"  :path "/api/mcp"            :handler handle-mcp-http}
     {:method "POST" :path "/api/mcp"            :handler handle-mcp-http}
     {:method "POST" :path "/api/reset"          :handler handle-reset}]))

;; ── SSR Entrypoint ─────────────────────────────────────────────────────────

(def *boot-ts* (str (sys-time-now)))

(defn app-component [req]
  (let [aot? (or (io/exists? "frontend/app.wasm") (io/exists? "opensunsama/frontend/app.wasm"))]
    [:html {:lang "en"}
      [:head
        [:title "Daily Planner & Time Blocking App | Open Sunsama"]
        [:meta {:charset "utf-8"}]
        [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0, viewport-fit=cover"}]
        [:meta {:name "description" :content "Plan tasks, block time around meetings, and focus on one thing. Open Sunsama is a daily planner with public code, self-hosting, and access for any AI agent."}]
        [:meta {:name "theme-color" :content "#f97316"}]
        [:link {:rel "preconnect" :href "https://fonts.googleapis.com"}]
        [:link {:rel "preconnect" :href "https://fonts.gstatic.com" :crossorigin "true"}]
        [:link {:rel "stylesheet" :href "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&family=Space+Grotesk:wght@500;600;700&display=swap"}]
        [:script {:src (str (if aot? "/coni_runtime.js?v=" "/wasm_exec.js?v=") *boot-ts*)}]
        [:link {:rel "stylesheet" :href (str "/style.css?v=" *boot-ts*)}]
        [:script {:type "module"}
          (if aot?
            (str "window.bootConiAOT('/app.wasm?v=" *boot-ts* "');")
            (str "initWasm(['/main.coni'], 'app', {wasmUrl: '/main.wasm?v=" *boot-ts* "'});"))]]
      [:body
        [:div {:id "app"}
          [:div {:style "display:flex;align-items:center;justify-content:center;min-height:100vh;background:#EFF1F5;color:#1F242D;font-family:Inter,system-ui,sans-serif;"}
            [:div {:style "text-align:center;padding:2.5rem;max-width:440px;background:#FFFFFF;border-radius:16px;box-shadow:0 10px 25px -5px rgba(16,24,40,0.08),0 0 0 1px rgba(16,24,40,0.05);"}
              [:div {:style "width:48px;height:48px;border-radius:12px;background:linear-gradient(135deg,#F97316,#FB923C);color:#fff;display:inline-flex;align-items:center;justify-content:center;font-weight:700;font-size:1.4rem;margin-bottom:1rem;box-shadow:0 8px 20px rgba(249,115,22,0.28);"} "☀️"]
              [:h2 {:style "font-weight:700;font-size:1.35rem;margin:0 0 0.5rem 0;letter-spacing:-0.02em;"} "Open Sunsama"]
              [:p {:style "color:#667085;font-size:0.9rem;line-height:1.55;margin:0;"} "Booting your AI-native daily planner, Kanban day columns, time-blocking calendar & 24-tool MCP connector..."]]]]]]))

;; ── Boot Server ────────────────────────────────────────────────────────────

(let [port-env (try (sys-env-get "CONIMO_PORT") (catch _ nil))
      port (if (and port-env (not= port-env "")) (read-string port-env) 3055)
      s-dir (if (io/exists? "frontend") "frontend/" "opensunsama/frontend/")]
  (conimo/start-app
    {:port port
     :static-dir s-dir
     :ssr-component app-component
     :api-router api-handler}))
