File size: 7,416 Bytes
c48360b
 
 
 
675b901
 
c48360b
675b901
 
 
 
c48360b
675b901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c48360b
 
675b901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c48360b
675b901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c48360b
 
675b901
 
 
 
 
c48360b
675b901
 
c48360b
 
 
675b901
c48360b
 
 
 
 
675b901
c48360b
675b901
 
c48360b
 
 
 
 
 
 
675b901
c48360b
 
675b901
 
 
c48360b
675b901
 
c48360b
675b901
 
c48360b
675b901
 
 
c48360b
 
675b901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c48360b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
window.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById("chat-form");
  const input = document.getElementById("user-input");
  const chatBox = document.getElementById("chat-box");
  const historyList = document.getElementById("history-list");
  const newChatBtn = document.getElementById("new-chat-btn"); // βœ… Use existing button

  let currentSession = null;

  // πŸ“† Format time
  function formatTime(iso) {
    try {
      const d = new Date(iso);
      return d.toLocaleString("en-IN", {
        hour: "numeric",
        minute: "2-digit",
        hour12: true,
        day: "2-digit",
        month: "short",
        year: "numeric",
      });
    } catch (err) {
      console.error("Error formatting time:", err);
      return "(no date)";
    }
  }

  // πŸ’Ύ Load full chat of selected session
  async function loadSession(sessionId) {
    try {
      const res = await fetch(`/history/${sessionId}`, {
        method: "GET",
        headers: { "Content-Type": "application/json" },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch history`);
      const data = await res.json();

      chatBox.innerHTML = "";
      currentSession = sessionId;

      if (data.length === 0) {
        chatBox.innerHTML = `<div class="msg bot-msg">No messages in this session yet.</div>`;
      } else {
        data.forEach(entry => {
          chatBox.innerHTML += `

            <div class="msg user-msg"><strong>You:</strong> ${entry.user}</div>

            <div class="msg bot-msg"><strong>Bot:</strong> ${entry.bot}</div>

          `;
        });
      }

      chatBox.scrollTop = chatBox.scrollHeight;

      // Highlight active session
      [...historyList.children].forEach(li => li.classList.remove("active"));
      const activeLi = document.querySelector(`[data-id="${sessionId}"]`);
      if (activeLi) activeLi.classList.add("active");

    } catch (err) {
      console.error(`Error loading session ${sessionId}:`, err);
      chatBox.innerHTML = `<div class="msg bot-msg">⚠️ Could not load chat session: ${err.message}</div>`;
    }
  }

  // πŸ“œ Load all session summaries
  async function loadHistory() {
    try {
      const res = await fetch("/sessions", {
        method: "GET",
        headers: { "Content-Type": "application/json" },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch sessions`);
      const sessions = await res.json();

      historyList.innerHTML = "";

      if (sessions.length === 0) {
        historyList.innerHTML = "<li>No chat sessions available.</li>";
        return;
      }

      sessions.forEach(s => {
        const li = document.createElement("li");
        li.className = "session-entry";
        li.setAttribute("data-id", s.session_id);

        const formatted = s.created_at ? formatTime(s.created_at) : "(no date)";
        li.innerHTML = `

          <span class="session-text">${formatted}</span>

          <button class="delete-btn" title="Delete">πŸ—‘οΈ</button>

        `;

        // βœ… Load session on click
        li.querySelector(".session-text").addEventListener("click", () => loadSession(s.session_id));

        // βœ… Delete session
        li.querySelector(".delete-btn").addEventListener("click", async (e) => {
          e.stopPropagation();
          if (confirm("πŸ—‘οΈ Delete this chat session?")) {
            try {
              const res = await fetch(`/sessions/${s.session_id}`, {
                method: "DELETE",
                headers: { "Content-Type": "application/json" },
              });
              if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to delete session`);
              if (s.session_id === currentSession) {
                chatBox.innerHTML = `<div class="msg bot-msg">Chat session deleted.</div>`;
                currentSession = null;
              }
              loadHistory();
            } catch (err) {
              console.error(`Error deleting session ${s.session_id}:`, err);
              alert(`Failed to delete session: ${err.message}`);
            }
          }
        });

        historyList.appendChild(li);
      });

      // Load the current session if it exists
      if (currentSession) {
        loadSession(currentSession);
      }

    } catch (err) {
      console.error("Error loading sessions:", err);
      historyList.innerHTML = `<li>⚠️ Failed to load chat sessions: ${err.message}</li>`;
    }
  }

  // πŸ“ Handle new message submission
  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    const message = input.value.trim();
    if (!message) return;

    chatBox.innerHTML += `<div class="msg user-msg"><strong>You:</strong> ${message}</div>`;
    input.value = "";
    input.disabled = true;
    chatBox.scrollTop = chatBox.scrollHeight;

    try {
      const response = await fetch("/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message }),
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}: Failed to send message`);

      const data = await response.json();
      const botResponse = data.response || data.error || "⚠️ No response";

      chatBox.innerHTML += `<div class="msg bot-msg"><strong>Bot:</strong> ${botResponse}</div>`;
      chatBox.scrollTop = chatBox.scrollHeight;

      loadHistory(); // Refresh session list to include new messages
    } catch (error) {
      console.error("Error sending message:", error);
      chatBox.innerHTML += `<div class="msg bot-msg">⚠️ Error getting response: ${error.message}</div>`;
    }

    input.disabled = false;
    input.focus();
  });

  // βž• Create new chat session
  newChatBtn.addEventListener("click", async () => {
    try {
      const res = await fetch("/new_session", {
        method: "GET",
        headers: { "Content-Type": "application/json" },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to create new session`);
      const data = await res.json();
      currentSession = data.session_id;
      chatBox.innerHTML = `<div class="msg bot-msg">New chat session started.</div>`;
      await loadHistory();
      await loadSession(currentSession);
    } catch (err) {
      console.error("Error creating new session:", err);
      chatBox.innerHTML = `<div class="msg bot-msg">⚠️ Failed to create new session: ${err.message}</div>`;
    }
  });

  // πŸš€ Initialize: Load current session history
  async function init() {
    try {
      const res = await fetch("/history", {
        method: "GET",
        headers: { "Content-Type": "application/json" },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch current session`);
      const data = await res.json();
      if (data.length > 0) {
        currentSession = data[0].session_id; // Assume session_id is consistent in backend
        await loadSession(currentSession);
      }
      await loadHistory();
    } catch (err) {
      console.error("Error initializing:", err);
      chatBox.innerHTML = `<div class="msg bot-msg">⚠️ Could not initialize chat: ${err.message}</div>`;
    }
  }

  init();
});