#!/usr/bin/env python3
"""ObesityWithdrawnRevive-Kor -- Streamlit UI

Thin UI wrapper around the same offline logic as main.py. No network calls.
Run:  streamlit run app.py

DISCLAIMER: Reference / research hypothesis-generation tool only.
NOT clinical decision support. NOT medical advice.
"""

import os
import sys

import streamlit as st

# optional graph viz; degrade gracefully if absent
try:
    import networkx as nx
    HAVE_NX = True
except Exception:
    HAVE_NX = False

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import main as core  # reuse all stdlib logic


@st.cache_data
def get_data():
    return core.load_data()


def harm_names(data, ids):
    return core.harm_names(data, ids)


def main():
    st.set_page_config(page_title="ObesityWithdrawnRevive-Kor",
                       layout="wide")
    data = get_data()
    m = data["_meta"]

    st.title("ObesityWithdrawnRevive-Kor")
    st.caption("Domain: %s  |  %s" % (m["domain"], m["category"]))
    st.warning("DISCLAIMER: " + core.DISCLAIMER +
               " Curated from public historical facts; scored fields are "
               "SYNTHETIC DEMO content.")

    tab1, tab2, tab3, tab4, tab5 = st.tabs([
        "1. Registry",
        "2. Harm Ontology",
        "3. De-risking Hypotheses",
        "4. Inheritance Tracker",
        "5. Summary",
    ])

    # --- Tab 1: registry --------------------------------------------------- #
    with tab1:
        st.subheader("Withdrawn / discontinued anti-obesity registry")
        rows = []
        for d in data["drugs"]:
            rows.append({
                "drug": d["name"],
                "class": d["class"],
                "status": d["status"],
                "year": d["event_year"],
                "targets": ", ".join(d["targets"]),
                "reason": d["withdrawal_reason"],
                "harm": "; ".join(harm_names(data, d["harm_nodes"])),
                "grade": d["evidence_grade"],
            })
        st.dataframe(rows, use_container_width=True)

    # --- Tab 2: harm ontology --------------------------------------------- #
    with tab2:
        st.subheader("harm-mechanism ontology")
        for h in data["harm_mechanisms"]:
            with st.expander("%s  (%s)" % (h["name"], h["id"])):
                st.write("**Tissue:** %s" % h["tissue"])
                st.write("**Mechanism:** %s" % h["mechanism"])
                st.write("**Vulnerable groups:** %s"
                         % ", ".join(h["vulnerable_groups"]))
                linked = [d["name"] for d in data["drugs"]
                          if h["id"] in d["harm_nodes"]]
                st.write("**Linked drugs:** %s" % ", ".join(linked))
        if HAVE_NX:
            g = nx.DiGraph()
            for d in data["drugs"]:
                for hid in d["harm_nodes"]:
                    g.add_edge(d["name"], data["_harm_by_id"][hid]["name"])
            st.caption("ontology graph: %d nodes / %d harm edges"
                       % (g.number_of_nodes(), g.number_of_edges()))
        else:
            st.info("networkx not installed -- graph metrics skipped "
                    "(ontology data still shown above).")

    # --- Tab 3: de-risking hypotheses ------------------------------------- #
    with tab3:
        st.subheader("Ranked de-risking hypotheses")
        names = ["(all drugs)"] + [d["name"] for d in data["drugs"]]
        pick = st.selectbox("Scope", names)
        top = st.slider("Top N", 1, 30, 8)
        if pick == "(all drugs)":
            hyps = core.all_hypotheses(data)
        else:
            drug = next(d for d in data["drugs"] if d["name"] == pick)
            hyps = core.build_hypotheses(data, drug)
        for i, h in enumerate(hyps[:top], 1):
            with st.expander("[%d] score %.3f  -  %s  <-  %s"
                             % (i, h["score"], h["lever"], h["drug"])):
                st.write("**Keep target(s):** %s" % h["targets_kept"])
                st.write("**Remove harm:** %s" % "; ".join(h["harm_addressed"]))
                st.write("**Hypothesis:** %s" % h["description"])
                st.write("**Precedent:** %s" % h["precedent"])
                st.write("**Validation design:** %s" % h["validation_design"])
                st.progress(min(1.0, h["score"]))

    # --- Tab 4: inheritance tracker --------------------------------------- #
    with tab4:
        st.subheader("Historical-harm inheritance tracker")
        st.write("Describe a next-gen candidate (class / target / central vs "
                 "peripheral). Example: `central CB1 inverse agonist` or "
                 "`peripherally restricted CB1 agonist`.")
        q = st.text_input("Candidate descriptor",
                          value="central CB1 inverse agonist")
        if q.strip():
            flags = core.inheritance_risk(data, q)
            if not flags:
                st.info("No historical harm class matched. Try terms like "
                        "CB1, 5-HT2B, sympathomimetic, MetAP2, uncoupler.")
            for f in flags:
                st.markdown("**Class %s -- inherited risk: %s**"
                            % (f["class"], f["risk_level"]))
                st.write("Harm nodes: %s" % "; ".join(f["harm_nodes"]))
                st.write("Ancestors: %s" % ", ".join(f["ancestor_drugs"]))
                st.write("Monitoring hypothesis: %s"
                         % f["monitoring_hypothesis"])
                st.divider()

    # --- Tab 5: summary --------------------------------------------------- #
    with tab5:
        st.subheader("Summary")
        c1, c2, c3, c4 = st.columns(4)
        c1.metric("Drugs/candidates", len(data["drugs"]))
        c2.metric("Harm mechanisms", len(data["harm_mechanisms"]))
        c3.metric("De-risking levers", len(data["de_risking_levers"]))
        c4.metric("Inheritance classes", len(data["inheritance_classes"]))
        st.write("**Open sources:** " + "; ".join(m["open_sources"]))
        st.write("**Note:** " + m["note"])


if __name__ == "__main__":
    main()
