import React, { useState, useEffect, useRef } from 'react'; import { useParams } from 'react-router-dom'; import '../App.css'; // Use relative URLs in production, full URLs in development const isDevelopment = window.location.hostname === 'localhost'; const API_URL = isDevelopment ? 'http://localhost:8000' : ''; interface Message { id: number; text: string; agent: string; } interface Podcast { id: number; title: string; description: string; audio_file: string; filename?: string; category?: string; } interface PodcastContext { topic: string; believer_chunks: string[]; skeptic_chunks: string[]; } const PodcastForm: React.FC = () => { const { id } = useParams<{ id: string }>(); const [podcast, setPodcast] = useState(null); const [podcastContext, setPodcastContext] = useState(null); const [messages, setMessages] = useState([]); const [inputMessage, setInputMessage] = useState(''); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(""); const messagesEndRef = useRef(null); useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]); useEffect(() => { const fetchPodcastAndContext = async () => { try { if (!id) return; // Fetch podcast details const response = await fetch(`${API_URL}/api/audio-list`); if (!response.ok) { throw new Error('Failed to fetch podcasts'); } const files = await response.json(); const podcastList = files.map((file: any, index: number) => { const filename = file.filename; const parts = filename.split('-'); let queryPart = '', descriptionPart = '', categoryWithExt = ''; if (parts.length >= 3) { [queryPart, descriptionPart, categoryWithExt] = parts; } else { queryPart = parts[0] || ''; descriptionPart = parts[1] || queryPart; categoryWithExt = parts[2] || 'general.mp3'; } const category = categoryWithExt.replace('.mp3', ''); return { id: index + 1, title: descriptionPart.replace(/_/g, ' ').replace(/^\w/, c => c.toUpperCase()), description: `A debate exploring ${queryPart.replace(/_/g, ' ')}`, audio_file: `${API_URL}${file.path}`, filename: filename, category: category.replace(/_/g, ' ') }; }); const selectedPodcast = podcastList.find(p => p.id === parseInt(id)); if (selectedPodcast) { setPodcast(selectedPodcast); // Fetch podcast context const contextResponse = await fetch(`${API_URL}/api/podcast/${id}/context`); if (contextResponse.ok) { const contextData: PodcastContext = await contextResponse.json(); setPodcastContext(contextData); } } } catch (err) { console.error('Error fetching podcast:', err); setError(err instanceof Error ? err.message : 'Failed to fetch podcast'); } }; fetchPodcastAndContext(); }, [id]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!inputMessage.trim() || !id) return; const userMessage: Message = { id: messages.length + 1, text: inputMessage, agent: "user" }; setMessages(prev => [...prev, userMessage]); setInputMessage(''); setIsLoading(true); try { const response = await fetch(`${API_URL}/api/podcast-chat/${id}`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: inputMessage }) }); if (!response.ok) { throw new Error(`Server error: ${response.status}`); } const data = await response.json(); const botMessage: Message = { id: messages.length + 2, text: data.response, agent: "assistant" }; setMessages(prev => [...prev, botMessage]); } catch (error) { console.error('Error sending message:', error); setMessages(prev => [...prev, { id: prev.length + 1, text: `Error: ${error instanceof Error ? error.message : 'Failed to send message'}`, agent: "system" }]); } finally { setIsLoading(false); } }; return (
{error && (
Error: {error}
)} {podcast && (

{podcast.title}

{podcast.category && (
{podcast.category}
)}

{podcast.description}

{podcastContext && (

Topic: {podcastContext.topic}

)}
)}
{messages.map((message) => (
{message.agent === "user" ? "👤" : message.agent === "system" ? "🤖" : message.agent === "assistant" ? "🤖" : "💬"}
{message.agent}
{message.text}
))} {isLoading && (
Processing
)}
setInputMessage(e.target.value)} placeholder="Ask a question about this podcast..." className="podcast-chat-input" disabled={isLoading} />
{podcastContext && (

Key Points

    {podcastContext.believer_chunks.map((chunk, i) => (
  • {chunk}
  • ))} {podcastContext.skeptic_chunks.map((chunk, i) => (
  • {chunk}
  • ))}
)}
); }; export default PodcastForm;