"""
ui/history_page.py
- History viewer
"""

import streamlit as st
from core.database import list_entries, get_entry, delete_entry, clear_all


KIND_ICON = {
    "video": "📥",
    "keywords": "🔑",
    "trending": "🔥",
    "analyze": "🧠",
    "compare": "⚖️",
}


def render_history():
    st.subheader("📚 History")
    st.caption("All your analyses stored locally")

    c1, c2 = st.columns([2, 1])
    kind = c1.selectbox("Filter", ["all", "video", "keywords", "trending", "analyze", "compare"])
    if c2.button("🗑 Clear all", use_container_width=True):
        clear_all(None if kind == "all" else kind)
        st.success("Cleared")
        st.rerun()

    entries = list_entries(None if kind == "all" else kind, limit=200)

    if not entries:
        st.info("No history yet")
        return

    for e in entries:
        icon = KIND_ICON.get(e["kind"], "📄")
        with st.expander(f"{icon} [{e['kind']}] {e['title'][:80]} — {e['created_at'][:16]}"):
            c1, c2 = st.columns([4, 1])
            with c1:
                if e["url"]:
                    st.markdown(f"[{e['url']}]({e['url']})")
            with c2:
                if st.button("🗑 Delete", key=f"del_{e['id']}"):
                    delete_entry(e["id"])
                    st.rerun()

            detail = get_entry(e["id"])
            if detail:
                st.json(detail["data"])