import gradio as gr
import pandas as pd
import numpy as np
from scipy.fft import fft, fftfreq

# Core Analysis Functions
def detect_cycles(data):
    N = len(data)
    yf = fft(data)
    xf = fftfreq(N, 1)[:N//2]
    dominant_freq = xf[np.argmax(np.abs(yf[0:N//2]))]
    return int(1/dominant_freq)

def analyze_data(url):
    try:
        df = pd.read_csv(url)
        values = df.sum(numeric_only=True).diff().fillna(0).values
        return {
            "cycles": detect_cycles(values),
            "trend": "↑ Increasing" if values[-1] > values[-30] else "↓ Decreasing"
        }
    except Exception as e:
        return {"error": str(e)}

# Chatbot Logic
def respond(message, history):
    if "analyze" in message.lower():
        url = message.split()[-1]
        result = analyze_data(url)
        
        if "error" in result:
            return f"❌ Error: {result['error']}"
            
        return f"""**Analysis Results:**
        - 🔄 Dominant Cycle: {result['cycles']} days
        - 📈 30-Day Trend: {result['trend']}
        """

    elif any(w in message.lower() for w in ["hi", "hello", "help"]):
        return """**Welcome to DeepSeek Analyst!** 🤖
        Send me a CSV URL to analyze time-series data. Example:
        `analyze https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/data/time_series_covid19_confirmed_global.csv`
        """
        
    return "I specialize in data analysis. Send me a CSV URL to get started!"

# Gradio Interface
gr.ChatInterface(
    respond,
    chatbot=gr.Chatbot(height=400),
    textbox=gr.Textbox(placeholder="Paste CSV URL here...", scale=7),
    title="DeepSeek Analysis Chatbot",
    description="Upload or paste CSV URLs to detect cycles and trends",
    examples=[[
        "analyze https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/data/time_series_covid19_confirmed_global.csv"
    ]],
    theme="soft",
    retry_btn=None,
    undo_btn=None,
    clear_btn="🗑️ Clear"
).launch()