import random

import gradio as gr
from huggingface_hub import list_models

GUESTS = {
    "ada lovelace": {
        "name": "Lady Ada Lovelace",
        "relation": "esteemed mathematician and friend",
        "description": (
            "Renowned for pioneering work in mathematics and computing, often "
            "celebrated as the first computer programmer for her notes on Charles "
            "Babbage's Analytical Engine."
        ),
        "email": "ada.lovelace@example.com",
    },
    "nikola tesla": {
        "name": "Dr. Nikola Tesla",
        "relation": "old friend from university days",
        "description": (
            "Recently patented a new wireless energy transmission system and would "
            "be delighted to discuss it. He is passionate about pigeons."
        ),
        "email": "nikola.tesla@gmail.com",
    },
    "marie curie": {
        "name": "Marie Curie",
        "relation": "scientific guest of honour",
        "description": "Pioneer of radioactivity research. Keep the conversation on science, not gossip.",
        "email": "marie.curie@example.com",
    },
}


def guest_info(query: str) -> str:
    q = query.lower()
    for key, guest in GUESTS.items():
        if key in q or guest["name"].lower() in q:
            return (
                f"Name: {guest['name']}\n"
                f"Relation: {guest['relation']}\n"
                f"{guest['description']}\n"
                f"Email: {guest['email']}"
            )
    return "No matching guest found in the invitee list."


def weather_info(location: str) -> str:
    conditions = [
        {"condition": "Rainy", "temp_c": 15},
        {"condition": "Clear", "temp_c": 25},
        {"condition": "Windy", "temp_c": 20},
    ]
    data = random.choice(conditions)
    suitable = (
        "suitable for fireworks"
        if data["condition"] == "Clear"
        else "not ideal for fireworks"
    )
    return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C. Conditions are {suitable}."


def hub_stats(author: str) -> str:
    try:
        models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
        if models:
            model = models[0]
            return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads."
        return f"No models found for author {author}."
    except Exception as exc:
        return f"Error fetching models for {author}: {exc}"


def alfred(message: str, history: list) -> str:
    text = message.lower()
    observations = []

    if any(name in text for name in ("ada", "lovelace", "tesla", "curie", "guest")):
        observations.append(guest_info(message))
    if "weather" in text or "firework" in text:
        location = "Paris"
        for city in ("paris", "london", "new york"):
            if city in text:
                location = city.title()
        observations.append(weather_info(location))
    if "model" in text or "hub" in text or "qwen" in text or "facebook" in text or "google" in text:
        author = "Qwen"
        if "facebook" in text:
            author = "facebook"
        elif "google" in text:
            author = "google"
        observations.append(hub_stats(author))

    if not observations:
        observations.append(
            "I can look up gala guests, weather for fireworks, and Hugging Face Hub stats. "
            "Try: 'Tell me about Lady Ada Lovelace' or 'What's the weather in Paris tonight?'"
        )

    return "🎩 Alfred:\n\n" + "\n\n".join(observations)


demo = gr.ChatInterface(
    fn=alfred,
    title="Alfred — Gala Agentic RAG",
    description="Unit 3 use case: guest RAG, weather, and Hub stats for the gala.",
)

if __name__ == "__main__":
    demo.launch()
