"""
Cat Health & Nutrition Dashboard
================================
A complete, single-file Streamlit web application for the CatTravellers project.

Features
--------
1. Calorie Intake Calculator
   - Weight entry with a kg / lbs toggle.
   - Life-stage selection with the requested RER x multiplier method.
   - RER = 70 * (weight_kg ** 0.75)
   - MER = RER * life_stage_multiplier
   - Multipliers: Kitten (2.5), Neutered Adult (1.2), Unneutered Adult (1.4),
     Sedentary/Prone to weight gain (1.0), Active (1.4), Senior (1.1).

2. Food Toxicity & Safety Checker
   - Text search against a local dictionary of 20 common human foods.
   - Each food is classified as "Toxic", "Caution" or "Safe".
   - st.error() for Toxic, st.warning() for Caution, st.success() for Safe.
   - Fallback for unknown foods: a clear "safety unknown" mock response with a
     prominent link back to https://cattravellers.com/blog for guidance.

Run locally
-----------
    pip install streamlit
    streamlit run cat_health_dashboard.py

Deploy
------
Push this file to a GitHub repo and connect it on Streamlit Cloud.

Legal
-----
This tool provides general educational guidance only and is not a substitute
for professional veterinary advice. Always consult a licensed veterinarian
for advice tailored to your cat.
"""

from __future__ import annotations

import streamlit as st

BLOG_URL = "https://cattravellers.com/blog"

# ---------------------------------------------------------------------------
# Data
# ---------------------------------------------------------------------------

LIFE_STAGES = {
    "Kitten": {"multiplier": 2.5, "note": "Growing kittens need the most energy per kg."},
    "Neutered Adult": {"multiplier": 1.2, "note": "The most common adult profile."},
    "Unneutered Adult": {"multiplier": 1.4, "note": "Slightly higher energy needs."},
    "Sedentary/Prone to weight gain": {"multiplier": 1.0, "note": "Lower energy to manage weight."},
    "Active": {"multiplier": 1.4, "note": "Active, lean adults burn more."},
    "Senior": {"multiplier": 1.1, "note": "Older cats often need a little less."},
}

# Local food-safety database. Each entry: name, aliases, status, summary, detail.
FOOD_DATABASE = {
    "chocolate": {
        "aliases": ["cocoa", "cacao", "dark chocolate", "milk chocolate"],
        "status": "Toxic",
        "summary": "Never feed chocolate to a cat.",
        "detail": (
            "Chocolate contains theobromine and caffeine, which cats metabolise poorly. "
            "Even small amounts can cause vomiting, rapid heart rate, tremors and seizures."
        ),
    },
    "onions": {
        "aliases": ["onion", "garlic", "leek", "chives", "shallots", "scallions"],
        "status": "Toxic",
        "summary": "Onions, garlic, leeks and chives damage red blood cells.",
        "detail": (
            "All members of the Allium family contain compounds that destroy a cat's red "
            "blood cells, leading to anaemia. This applies raw, cooked, dried and powdered forms."
        ),
    },
    "grapes": {
        "aliases": ["grape", "raisins", "raisin", "sultanas", "currants"],
        "status": "Toxic",
        "summary": "Grapes and raisins can cause kidney failure.",
        "detail": (
            "Grapes and raisins are linked to acute kidney failure in pets. The toxic principle "
            "is not fully understood, so no amount is considered safe."
        ),
    },
    "xylitol": {
        "aliases": ["birch sugar", "sugar-free gum", "xylitol gum"],
        "status": "Toxic",
        "summary": "Xylitol (birch sugar) is extremely dangerous.",
        "detail": (
            "Xylitol - a common sugar-free sweetener in gum, sweets and some peanut butters - "
            "can cause a dangerous drop in blood sugar and liver damage."
        ),
    },
    "alcohol": {
        "aliases": ["ethanol", "beer", "wine", "liquor"],
        "status": "Toxic",
        "summary": "Alcohol is toxic to cats in any amount.",
        "detail": (
            "Even tiny amounts of alcohol can cause dangerous drops in blood sugar, blood "
            "pressure and body temperature, and may lead to respiratory failure."
        ),
    },
    "caffeine": {
        "aliases": ["coffee", "tea", "energy drink", "espresso"],
        "status": "Toxic",
        "summary": "Caffeine is unsafe for cats.",
        "detail": (
            "Coffee, tea, energy drinks and caffeine tablets can cause restlessness, rapid "
            "breathing, heart palpitations and muscle tremors in cats."
        ),
    },
    "raw bread dough": {
        "aliases": ["raw dough", "yeast dough"],
        "status": "Toxic",
        "summary": "Raw yeast dough expands and ferments inside the stomach.",
        "detail": (
            "Raw bread dough can swell in the stomach and produce alcohol as it ferments, "
            "causing painful bloating and alcohol toxicity."
        ),
    },
    "milk": {
        "aliases": ["cow milk", "dairy", "cream", "lactose"],
        "status": "Caution",
        "summary": "Most adult cats are lactose intolerant.",
        "detail": (
            "Many adult cats lack the enzyme to digest lactose, so cow's milk and cream can "
            "cause diarrhoea and stomach upset. Small amounts of lactose-free cat milk are safer."
        ),
    },
    "cheese": {
        "aliases": ["cheddar", "hard cheese", "soft cheese"],
        "status": "Caution",
        "summary": "Cheese is high in fat and lactose.",
        "detail": (
            "A tiny piece of hard cheese now and then is usually tolerated, but cheese is rich "
            "in fat and lactose and can trigger digestive upset or weight gain."
        ),
    },
    "tuna": {
        "aliases": ["canned tuna", "tinned tuna"],
        "status": "Caution",
        "summary": "Occasional tuna is fine; it is not a balanced diet.",
        "detail": (
            "A small amount of plain cooked tuna as an occasional treat is generally okay, but "
            "tuna for humans lacks full nutrition and can be high in mercury and salt."
        ),
    },
    "eggs": {
        "aliases": ["cooked egg", "scrambled egg", "boiled egg"],
        "status": "Caution",
        "summary": "Cooked eggs only - never raw.",
        "detail": (
            "Fully cooked eggs are a safe, protein-rich occasional treat. Raw or undercooked "
            "eggs carry a risk of Salmonella and contain avidin, which can interfere with "
            "nutrient absorption."
        ),
    },
    "bones": {
        "aliases": ["cooked bones", "chicken bones", "fish bones"],
        "status": "Caution",
        "summary": "Cooked bones can splinter dangerously.",
        "detail": (
            "Cooked bones - especially poultry and fish - can splinter and cause choking or "
            "internal punctures. Many vets advise avoiding them entirely."
        ),
    },
    "blueberries": {
        "aliases": ["blueberry"],
        "status": "Safe",
        "summary": "Blueberries are a safe, occasional treat.",
        "detail": (
            "Fresh or frozen blueberries are non-toxic and low in calories. Offer one or two "
            "as an occasional treat."
        ),
    },
    "strawberries": {
        "aliases": ["strawberry"],
        "status": "Safe",
        "summary": "Strawberries are safe in small amounts.",
        "detail": (
            "A small slice of strawberry is non-toxic and can be a sweet occasional treat. "
            "Remove the leafy top and offer only a little."
        ),
    },
    "banana": {
        "aliases": ["bananas"],
        "status": "Safe",
        "summary": "Bananas are safe in tiny portions.",
        "detail": (
            "A small piece of ripe banana is non-toxic. Because of the sugar content, keep it "
            "to an occasional pea-sized treat."
        ),
    },
    "carrots": {
        "aliases": ["carrot", "cooked carrots"],
        "status": "Safe",
        "summary": "Cooked carrots are safe and gentle.",
        "detail": (
            "Cooked, plain carrots are non-toxic and provide fibre and vitamins. Always cook or "
            "grate them finely, and serve without seasoning, butter or salt."
        ),
    },
    "pumpkin": {
        "aliases": ["cooked pumpkin", "pure pumpkin"],
        "status": "Safe",
        "summary": "Plain pumpkin is safe and aids digestion.",
        "detail": (
            "Plain, cooked pumpkin (not spiced pie filling) is non-toxic and often recommended "
            "in small amounts to support digestion."
        ),
    },
    "cooked chicken": {
        "aliases": ["chicken", "boiled chicken", "plain chicken"],
        "status": "Safe",
        "summary": "Plain cooked chicken is a safe, lean treat.",
        "detail": (
            "Plain, unseasoned cooked chicken is a safe and popular treat. Avoid skin, bones, "
            "salt, garlic and onion."
        ),
    },
    "salmon": {
        "aliases": ["cooked salmon"],
        "status": "Safe",
        "summary": "Cooked salmon is safe in small amounts.",
        "detail": (
            "Fully cooked, plain salmon is non-toxic and rich in healthy fats. Never serve it "
            "raw, and avoid smoked or seasoned salmon, which can be high in salt."
        ),
    },
    "watermelon": {
        "aliases": ["water melon"],
        "status": "Safe",
        "summary": "Seedless watermelon is a safe, hydrating treat.",
        "detail": (
            "Seedless watermelon flesh is non-toxic and mostly water. Remove all seeds and "
            "never offer the rind, which is hard to digest."
        ),
    },
}


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def find_food(query: str):
    """Return the matching database entry for a query, or None."""
    q = query.strip().lower()
    if not q:
        return None
    for name, entry in FOOD_DATABASE.items():
        candidates = [name] + entry["aliases"]
        for c in candidates:
            cl = c.lower()
            if cl == q or cl in q or q in cl:
                return {"name": name, **entry}
    return None


def calculate_rer(weight_kg: float) -> float:
    return 70 * (weight_kg ** 0.75)


# ---------------------------------------------------------------------------
# Page config & disclaimer
# ---------------------------------------------------------------------------

st.set_page_config(
    page_title="Cat Health & Nutrition Dashboard",
    page_icon="🐱",
    layout="wide",
)

st.title("🐱 Cat Health & Nutrition Dashboard")
st.caption("Calorie intake calculator & food toxicity safety checker for cats.")

st.warning(
    "**Legal disclaimer:** This dashboard offers general educational guidance only and is not a "
    "substitute for professional veterinary advice. Calorie estimates and food-safety results are "
    "approximations. Always consult a licensed veterinarian for advice tailored to your cat's age, "
    "weight, breed and health."
)

st.markdown("---")

# ---------------------------------------------------------------------------
# Feature 1: Calorie Intake Calculator
# ---------------------------------------------------------------------------

st.header("1. Calorie Intake Calculator")

with st.container(border=True):
    col_w, col_u = st.columns([3, 1])
    with col_u:
        unit = st.radio("Unit", ["kg", "lbs"], horizontal=True)
    with col_w:
        weight = st.number_input(
            f"Cat's weight ({unit})",
            min_value=0.0,
            value=4.5 if unit == "kg" else 10.0,
            step=0.1 if unit == "kg" else 0.25,
            format="%.2f",
        )

    life_stage = st.selectbox("Life stage", list(LIFE_STAGES.keys()))
    st.caption(LIFE_STAGES[life_stage]["note"])

    # Convert to kg
    weight_kg = weight * 0.45359237 if unit == "lbs" else weight

    if weight_kg <= 0:
        st.info("Enter a weight greater than zero to calculate daily calories.")
    else:
        rer = calculate_rer(weight_kg)
        multiplier = LIFE_STAGES[life_stage]["multiplier"]
        mer = rer * multiplier

        m1, m2, m3 = st.columns(3)
        m1.metric("Weight (kg)", f"{weight_kg:.2f} kg")
        m2.metric("RER (Resting Energy)", f"{rer:.0f} kcal")
        m3.metric("MER (Maintenance)", f"{mer:.0f} kcal/day")

        st.success(
            f"**Recommended daily calories: {mer:.0f} kcal/day**  \n"
            f"Calculated as RER ({rer:.0f}) x {life_stage} multiplier ({multiplier})."
        )
        st.caption(
            "Formula: RER = 70 x (weight kg)^0.75, then MER = RER x life-stage multiplier. "
            "Values are general educational estimates, not a prescription."
        )

st.markdown("---")

# ---------------------------------------------------------------------------
# Feature 2: Food Toxicity & Safety Checker
# ---------------------------------------------------------------------------

st.header("2. Food Toxicity & Safety Checker")

with st.container(border=True):
    query = st.text_input(
        "Search a food item",
        placeholder="e.g. chocolate, blueberries, onions...",
    )

    if query.strip():
        match = find_food(query)
        if match:
            status = match["status"]
            if status == "Toxic":
                st.error(f"**{match['name'].title()} — Toxic: do not feed.**\n\n{match['summary']}\n\n{match['detail']}")
            elif status == "Caution":
                st.warning(f"**{match['name'].title()} — Caution: feed with care.**\n\n{match['summary']}\n\n{match['detail']}")
            else:
                st.success(f"**{match['name'].title()} — Safe in moderation.**\n\n{match['summary']}\n\n{match['detail']}")
        else:
            st.warning(
                f"**\"{query}\" is not in our verified database.**\n\n"
                "We can't classify this food as safe, caution or toxic. Treat any unfamiliar food "
                "as potentially unsafe until a veterinarian confirms it. Many human foods contain "
                "ingredients that are harmful to cats even when they seem harmless to us.\n\n"
                f"For detailed, vet-reviewed guidance, read our blog: [{BLOG_URL}]({BLOG_URL})"
            )

    st.caption("Browse common foods in the database:")
    chips = " · ".join(
        f"{name} ({entry['status'][0]})" for name, entry in FOOD_DATABASE.items()
    )
    st.markdown(f"_{chips}_")

st.markdown("---")

st.markdown(
    f"Built for **CatTravellers**. Read more cat care & nutrition guides on the "
    f"[CatTravellers blog]({BLOG_URL})."
)
st.caption("General educational guidance only — always consult a veterinarian for individual needs.")
