{% extends base_template %}
{% block content %}
<div class="chat-container">
  <div class="chat-header">
    <h1><i class="fa fa-comments"></i> AI Assistant</h1>
    <div class="chat-controls">
      {% if graph_db_enabled %}
      <a href="{{ url_for('AirflowChatView.dbt_upload_interface') }}" class="btn btn-sm btn-warning">
        <i class="fa fa-upload"></i> DBT Upload
      </a>
      {% endif %}
      <button id="newChat" class="btn btn-sm btn-primary">
        <i class="fa fa-plus"></i> New Chat
      </button>
    </div>
  </div>

  <div class="chat-messages" id="chatMessages">
    <div class="welcome-message">
      <div class="message assistant-message">
        <div class="message-avatar">
          <i class="fa fa-robot"></i>
        </div>
        <div class="message-content">
          <div class="message-text">
            Hello! I'm your Airflow AI assistant.
            {% if graph_db_enabled %}
            <br><small><i class="fa fa-database"></i> Graph database is enabled - you can ask about DBT models and lineage.</small>
            {% endif %}
          </div>
          <div class="message-time">Just now</div>
        </div>
      </div>
    </div>
  </div>

  <div class="chat-input-container">
    <div class="chat-input-wrapper">
      <textarea 
        id="chatInput" 
        placeholder="Ask me anything about Airflow..." 
        rows="1"
        maxlength="2000"></textarea>
      <button id="sendButton" class="btn btn-primary" disabled>
        <i class="fa fa-paper-plane"></i>
      </button>
    </div>
    <div class="input-footer">
      <span class="char-count">0/2000</span>
      <span class="status" id="connectionStatus">Ready</span>
    </div>
  </div>
</div>

<style>
.chat-container {
  max-width: 1000px;
  margin: 0 auto;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.chat-controls a.btn {
  text-decoration: none;
  display: inline-block;
}

.chat-controls a.btn:hover {
  text-decoration: none;
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.chat-controls {
  display: flex;
  gap: 10px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
}

.message {
  display: flex;
  margin-bottom: 20px;
  max-width: 80%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.assistant-message {
  margin-right: auto;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 10px;
  font-size: 18px;
}

.user-message .message-avatar {
  background: #007bff;
  color: white;
}

.assistant-message .message-avatar {
  background: #6f42c1;
  color: white;
}

.message-content {
  flex: 1;
}

.message-text {
  background: #f1f3f4;
  padding: 12px 16px;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
}

.user-message .message-text {
  background: #007bff;
  color: white;
}

.assistant-message .message-text {
  background: #f1f3f4;
  color: #333;
}

.message-time {
  font-size: 11px;
  color: #666;
  margin-top: 4px;
  text-align: right;
}

.user-message .message-time {
  text-align: left;
}

.chat-input-container {
  background: white;
  border-top: 1px solid #e0e0e0;
  padding: 20px;
}

.chat-input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  max-width: 100%;
}

#chatInput {
  flex: 1;
  border: 2px solid #e0e0e0;
  border-radius: 20px;
  padding: 12px 16px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.4;
  max-height: 120px;
  transition: border-color 0.3s;
}

#chatInput:focus {
  outline: none;
  border-color: #007bff;
}

#sendButton {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  border: none;
  background: #007bff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

#sendButton:hover:not(:disabled) {
  background: #0056b3;
  transform: scale(1.05);
}

#sendButton:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

.char-count {
  font-size: 11px;
}

.status {
  font-weight: 500;
}

.status.connecting {
  color: #ffc107;
}

.status.ready {
  color: #28a745;
}

.status.error {
  color: #dc3545;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  background: #f1f3f4;
  border-radius: 18px;
  margin: 8px 0;
}

.typing-dots {
  display: flex;
  gap: 2px;
}

.typing-dot {
  width: 6px;
  height: 6px;
  background: #666;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

.welcome-message ul {
  margin: 10px 0;
  padding-left: 20px;
}

.welcome-message li {
  margin-bottom: 5px;
}

/* Tool execution styling */
.tool-execution {
  margin: 10px 0;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: #f8f9fa;
}

.tool-execution[open] {
  border-color: #007bff;
  background: #f0f8ff;
}

.tool-summary {
  padding: 12px 16px;
  cursor: pointer;
  font-weight: 600;
  color: #007bff;
  background: #f8f9fa;
  border-radius: 8px;
  user-select: none;
  transition: background-color 0.2s;
}

.tool-summary:hover {
  background: #e9ecef;
}

.tool-execution[open] .tool-summary {
  border-bottom: 1px solid #e0e0e0;
  border-radius: 8px 8px 0 0;
  background: #e3f2fd;
}

.tool-execution > div:not(.tool-summary) {
  padding: 16px;
}

.tool-execution pre {
  background: #2d3748;
  color: #e2e8f0;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 8px 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.4;
}

.tool-execution code {
  background: #f1f3f4;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
}

.tool-execution h1,
.tool-execution h2,
.tool-execution h3 {
  margin: 16px 0 8px 0;
  color: #333;
}

.tool-execution ul {
  margin: 8px 0;
  padding-left: 20px;
}

.tool-execution li {
  margin: 4px 0;
  list-style-type: disc;
}

/* Formatting styles */
.message-text h1,
.message-text h2,
.message-text h3 {
  margin: 16px 0 8px 0;
  color: #333;
  line-height: 1.3;
}

.message-text h1 { font-size: 1.5em; font-weight: 700; }
.message-text h2 { font-size: 1.3em; font-weight: 600; }
.message-text h3 { font-size: 1.1em; font-weight: 600; }

.message-text strong {
  font-weight: 600;
  color: #333;
}

.message-text code {
  background: #f1f3f4;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: #d63384;
}

.message-text pre {
  background: #2d3748;
  color: #e2e8f0;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 12px 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.4;
}

.message-text pre code {
  background: none;
  padding: 0;
  color: inherit;
  border-radius: 0;
}

.message-text ul,
.message-text ol {
  margin: 8px 0;
  padding-left: 20px;
}

.message-text li {
  margin: 4px 0;
  line-height: 1.4;
}

.message-text ul li {
  list-style-type: disc;
}

.message-text ol li {
  list-style-type: decimal;
}

@media (max-width: 768px) {
  .chat-container {
    height: calc(100vh - 80px);
    margin: 0;
    border-radius: 0;
  }
  
  .message {
    max-width: 90%;
  }
  
  .chat-header {
    padding: 15px;
  }
  
  .chat-header h1 {
    font-size: 20px;
  }
}
</style>

<script>
class AirflowChatClient {
  constructor() {
    this.conversationId = null;
    this.isConnected = true;
    this.currentStream = null;
    this.isStreaming = false; // Track streaming state
    
    this.initializeElements();
    this.attachEventListeners();
    this.autoResize();
  }
  
  initializeElements() {
    this.chatInput = document.getElementById('chatInput');
    this.sendButton = document.getElementById('sendButton');
    this.chatMessages = document.getElementById('chatMessages');
    this.newChatBtn = document.getElementById('newChat');
    this.charCount = document.querySelector('.char-count');
    this.status = document.getElementById('connectionStatus');
  }
  
  attachEventListeners() {
    // Send message events
    this.sendButton.addEventListener('click', () => this.sendMessage());
    this.chatInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        this.sendMessage();
      }
    });
    
    // Input events
    this.chatInput.addEventListener('input', () => {
      this.updateCharCount();
      this.updateSendButton();
      this.autoResize();
    });
    
    this.newChatBtn.addEventListener('click', () => this.newChat());
  }
  
  updateCharCount() {
    const length = this.chatInput.value.length;
    this.charCount.textContent = `${length}/2000`;
    
    if (length > 1800) {
      this.charCount.style.color = '#dc3545';
    } else if (length > 1500) {
      this.charCount.style.color = '#ffc107';
    } else {
      this.charCount.style.color = '#666';
    }
  }
  
  updateSendButton() {
    const hasText = this.chatInput.value.trim().length > 0;
    // Disable button if no text, not connected, or currently streaming
    this.sendButton.disabled = !hasText || !this.isConnected || this.isStreaming;
  }
  
  autoResize() {
    this.chatInput.style.height = 'auto';
    this.chatInput.style.height = Math.min(this.chatInput.scrollHeight, 120) + 'px';
  }
  
  setStatus(text, className = 'ready') {
    this.status.textContent = text;
    this.status.className = `status ${className}`;
  }
  
  setStreaming(streaming) {
    this.isStreaming = streaming;
    this.updateSendButton();
  }
  
  async sendMessage() {
    const message = this.chatInput.value.trim();
    if (!message || !this.isConnected || this.isStreaming) return;
    
    // Set streaming state to true
    this.setStreaming(true);
    
    // Initialize conversation if not exists
    if (!this.conversationId) {
      this.setStatus('Initializing chat...', 'connecting');
      try {
        const initResponse = await fetch("{{ url_for('AirflowChatView.new_chat') }}", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
          }
        });
        
        const initData = await initResponse.json();
        if (initData.conversation_id) {
          this.conversationId = initData.conversation_id;
        } else {
          throw new Error('Failed to initialize chat session');
        }
      } catch (error) {
        console.error('Failed to initialize chat:', error);
        this.setStatus('Failed to initialize chat', 'error');
        this.setStreaming(false); // Re-enable button on error
        return;
      }
    }
    
    // Add user message to chat
    this.addMessage(message, 'user');
    
    // Clear input
    this.chatInput.value = '';
    this.updateCharCount();
    this.updateSendButton();
    this.autoResize();
    
    // Show typing indicator
    const typingElement = this.showTypingIndicator();
    
    try {
      this.setStatus('Sending...', 'connecting');
      console.log('this.conversationId')
      console.log(this.conversationId)
      const response = await fetch("{{ url_for('AirflowChatView.chat_api') }}", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRFToken': '{{ csrf_token() }}'
        },
        body: JSON.stringify({
          message: message,
          conversation_id: this.conversationId
        })
      });
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      // Remove typing indicator
      this.removeTypingIndicator(typingElement);
      
      // Handle streaming response
      await this.handleStreamingResponse(response);
      
    } catch (error) {
      console.error('Chat error:', error);
      this.removeTypingIndicator(typingElement);
      this.addMessage(`Sorry, I encountered an error: ${error.message}`, 'assistant', true);
      this.setStatus('Error', 'error');
    } finally {
      // Always re-enable button when done
      this.setStreaming(false);
    }
  }
  
  async handleStreamingResponse(response) {
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let assistantMessage = '';
    let messageElement = null;
    
    this.setStatus('Receiving...', 'connecting');
    
    try {
      while (true) {
        const { done, value } = await reader.read();
        
        if (done) break;
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            
            if (data === '[DONE]') {
              this.setStatus('Ready', 'ready');
              return;
            }
            
            try {
              const parsed = JSON.parse(data);
              
            //   if (parsed.conversation_id && !this.conversationId) {
            //     this.conversationId = parsed.conversation_id;
            //   }
              
              if (parsed.content) {
                assistantMessage += parsed.content;
                
                if (!messageElement) {
                  messageElement = this.addMessage('', 'assistant');
                }
                
                this.updateMessage(messageElement, assistantMessage);
              }
              
              if (parsed.error) {
                this.setStatus('Error', 'error');
              }
              
            } catch (e) {
              console.warn('Failed to parse chunk:', data);
            }
          }
        }
      }
    } catch (error) {
      console.error('Streaming error:', error);
      this.addMessage('Sorry, the connection was interrupted.', 'assistant', true);
    } finally {
      this.setStatus('Ready', 'ready');
    }
  }
  
  addMessage(text, sender, isError = false) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}-message`;
    
    const now = new Date();
    const timeStr = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    
    // Parse markdown for better formatting
    const formattedText = this.parseMarkdown(text);
    
    messageDiv.innerHTML = `
      <div class="message-avatar">
        <i class="fa fa-${sender === 'user' ? 'user' : 'robot'}"></i>
      </div>
      <div class="message-content">
        <div class="message-text${isError ? ' error' : ''}">${formattedText}</div>
        <div class="message-time">${timeStr}</div>
      </div>
    `;
    
    this.chatMessages.appendChild(messageDiv);
    this.scrollToBottom();
    
    return messageDiv;
  }
  
  updateMessage(messageElement, text) {
    const textElement = messageElement.querySelector('.message-text');
    
    // Parse markdown-like formatting
    const formattedText = this.parseMarkdown(text);
    textElement.innerHTML = formattedText;
    
    this.scrollToBottom();
  }
  
  parseMarkdown(text) {
    // Convert basic markdown to HTML
    let html = text
      // Headers
      .replace(/^### (.*$)/gm, '<h3>$1</h3>')
      .replace(/^## (.*$)/gm, '<h2>$1</h2>')
      .replace(/^# (.*$)/gm, '<h1>$1</h1>')
      
      // Bold
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      
      // Code blocks
      .replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>')
      .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
      
      // Inline code
      .replace(/`([^`]+)`/g, '<code>$1</code>')
      
      // Lists
      .replace(/^\d+\.\s+(.*)$/gm, '<li>$1</li>')
      .replace(/^[\*\-]\s+(.*)$/gm, '<li>$1</li>')
      
      // Line breaks
      .replace(/\n/g, '<br>');
    
    // Wrap lists
    html = html.replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>');
    
    // Handle details/summary (collapsible sections)
    html = html.replace(/<details>/g, '<details class="tool-execution">')
               .replace(/<summary>/g, '<summary class="tool-summary">');
    
    return html;
  }
  
  showTypingIndicator() {
    const typingDiv = document.createElement('div');
    typingDiv.className = 'message assistant-message typing-message';
    typingDiv.innerHTML = `
      <div class="message-avatar">
        <i class="fa fa-robot"></i>
      </div>
      <div class="message-content">
        <div class="typing-indicator">
          <span>AI is thinking</span>
          <div class="typing-dots">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
          </div>
        </div>
      </div>
    `;
    
    this.chatMessages.appendChild(typingDiv);
    this.scrollToBottom();
    return typingDiv;
  }
  
  removeTypingIndicator(element) {
    if (element && element.parentNode) {
      element.parentNode.removeChild(element);
    }
  }
  
  clearChat() {
    if (confirm('Are you sure you want to clear the chat history?')) {
      // Keep the welcome message
      const welcomeMessage = this.chatMessages.querySelector('.welcome-message');
      this.chatMessages.innerHTML = '';
      if (welcomeMessage) {
        this.chatMessages.appendChild(welcomeMessage);
      }
      this.conversationId = null;
    }
  }
  
  newChat() {
    // Call the new chat API endpoint
    fetch("{{ url_for('AirflowChatView.new_chat') }}", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': '{{ csrf_token() }}'
      }
    })
    .then(response => response.json())
    .then(data => {
      if (data.conversation_id) {
        // this.conversationId = data.conversation_id;
        this.clearChat();
        this.setStatus('New chat initialized', 'ready');
      } else {
        console.error('Failed to initialize new chat:', data);
        this.setStatus('Failed to create new chat', 'error');
      }
    })
    .catch(error => {
      console.error('Error creating new chat:', error);
      this.setStatus('Error creating new chat', 'error');
    });
  }
  
  scrollToBottom() {
    this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
  }
  
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}

// Initialize chat when page loads
document.addEventListener('DOMContentLoaded', () => {
  new AirflowChatClient();
});
</script>
{% endblock %}