"""Read-only warehouse-runtime Streamlit consumer. Native execution NOT RUN.

All database identifiers and result fields are fixed here; there is no arbitrary SQL
input, connector, credential loading, source mutation, polling or fallback dataset.
"""
from datetime import datetime, timezone

DATABASE = "SF_EVAL_REVIEW_20261105"
CAP = 10000
PAGES = ("EXECUTIVE", "SPEND", "PERFORMANCE", "SECURITY", "OPERATIONS")
SIGNAL_COLUMNS = (
    "DOMAIN", "PRACTICE_ID", "CHECK_ID", "OBJECT_TYPE", "OBJECT_NAME",
    "SUBJECT_NAME", "OBSERVED_VALUE", "UNIT", "SIGNAL", "NEXT_ACTION", "DETAILS_JSON",
    "WINDOW_START_UTC", "WINDOW_END_UTC", "SOURCE_MODE", "SOURCE_CAPTURED_AT_UTC",
    "SOURCE_STATUS", "SOURCE_NAME", "ASSESSMENT_RUN_ID",
)
COVERAGE_COLUMNS = (
    "CHECK_ID", "PRACTICE_ID", "SOURCE_NAME", "SOURCE_MODE", "SOURCE_STATUS",
    "SOURCE_CAPTURED_AT_UTC", "WINDOW_START_UTC", "WINDOW_END_UTC", "ASSESSMENT_RUN_ID",
)
ALLOWLIST = {
    **{f"V_DASHBOARD_{page}": SIGNAL_COLUMNS for page in PAGES},
    "V_ALL_SIGNALS": SIGNAL_COLUMNS,
    "V_COVERAGE": COVERAGE_COLUMNS,
}
PROVENANCE_COLUMNS = (
    "WINDOW_START_UTC", "WINDOW_END_UTC", "SOURCE_MODE", "SOURCE_STATUS",
    "SOURCE_CAPTURED_AT_UTC", "SOURCE_NAME", "ASSESSMENT_RUN_ID",
)


def select_sql(view):
    """Only literal allowlisted views; no user-derived database/SQL fragments."""
    if view not in ALLOWLIST:
        raise ValueError("View is not allowlisted")
    order = "CHECK_ID, PRACTICE_ID, SOURCE_NAME"
    if view != "V_COVERAGE":
        order += ", OBJECT_NAME, SUBJECT_NAME"
    return (
        "SELECT " + ", ".join(ALLOWLIST[view])
        + f" FROM {DATABASE}.REPORTING.{view} ORDER BY {order} LIMIT {CAP}"
    )


def fetch_frame(session, view):
    """Propagate errors; caller must display failure instead of fake data."""
    sql = select_sql(view)
    frame = session.sql(sql).to_pandas()
    if tuple(frame.columns) != ALLOWLIST[view]:
        raise ValueError("Reporting view schema does not match contract")
    return frame


def capture_age_hours(value, now):
    """None is unknown, never a zero-age capture. Future captures are flagged."""
    if value is None:
        return None
    import pandas as pd
    stamp = pd.to_datetime(value, utc=True, errors="coerce")
    if pd.isna(stamp):
        return None
    return (now - stamp.to_pydatetime()).total_seconds() / 3600


def show_provenance(st, frame):
    now = datetime.now(timezone.utc)
    provenance = frame[list(PROVENANCE_COLUMNS)].drop_duplicates().copy()
    provenance["CAPTURE_AGE_HOURS_AT_RENDER"] = provenance["SOURCE_CAPTURED_AT_UTC"].map(
        lambda value: capture_age_hours(value, now)
    )
    st.caption(f"Rendered UTC: {now.isoformat()}. Capture age is elapsed time, not a source completeness guarantee.")
    st.dataframe(provenance)
    ages = provenance["CAPTURE_AGE_HOURS_AT_RENDER"]
    if ages.isna().any():
        st.warning("At least one capture timestamp is unknown. Its freshness cannot be established.")
    if (ages < 0).any():
        st.warning("A capture timestamp is in the future; verify source provenance and clock.")
    if (ages > 24).any():
        st.warning("At least one capture is over 24 hours old. This is an age reminder, not an expiry policy; inspect source status and the approved register.")
    st.caption("SOURCE_STATUS is authoritative coverage context. Missing, denied, partial, expired or unsupported evidence remains UNKNOWN. Polling copied metadata never updates its original capture/window.")


def render_numeric(st, frame):
    # Separate every check/unit. Never sum credits with bytes, hierarchy depth,
    # assignments, repeated practice mappings or UNKNOWN placeholder rows.
    numeric = frame[frame["OBSERVED_VALUE"].notna() & frame["SIGNAL"].isin(["CANDIDATE", "CONTEXT"])].copy()
    if numeric.empty:
        st.info("No measured candidate/context values available for a chart. Inspect the table and source coverage.")
        return
    for (check, unit), group in numeric.groupby(["CHECK_ID", "UNIT"], dropna=False, sort=True):
        # A check may map to several practices/sources: show one exact observation.
        fields = ["OBJECT_NAME", "SUBJECT_NAME", "OBSERVED_VALUE", "UNIT", "SIGNAL"]
        chart = group[fields].drop_duplicates().head(30).copy()
        chart["OBSERVATION"] = chart["OBJECT_NAME"].fillna("(unknown object)").astype(str) + " | " + chart["SUBJECT_NAME"].fillna("(unknown subject)").astype(str)
        st.caption(f"{check}: {unit}; first 30 distinct observations, no cross-check aggregation. Full returned population below.")
        st.bar_chart(chart, x="OBSERVATION", y="OBSERVED_VALUE")


def display_view(st, session, view):
    try:
        frame = fetch_frame(session, view)
    except Exception:
        st.error(f"{view}: query failed, access denied, or reporting schema incompatible. Coverage UNKNOWN. No replacement data was used; obtain secure query diagnostics from the owner.")
        return
    st.caption(f"Returned {len(frame)} rows; result cap {CAP}. This cap does not bound source compute. Views enforce configured observation windows; source scans can still cost credits.")
    if len(frame) >= CAP:
        st.warning("Result cap reached: population may be truncated. Never treat this as a complete account total.")
    if frame.empty:
        st.warning("Empty result population: UNKNOWN. Verify grants, source registration, observation window and native feature support.")
        return
    show_provenance(st, frame)
    if view != "V_COVERAGE":
        render_numeric(st, frame)
    st.dataframe(frame)


def main():
    import streamlit as st
    st.title("Snowflake assessment — SQL evidence")
    st.caption("Native deployment/execution NOT RUN during toolkit construction. Warehouse runtime required.")
    st.info("Manual refresh only. Opening this app does not execute assessment queries. No health score, verified compliance verdict, savings estimate or automated remediation is produced.")
    st.warning("Review the app owner's source visibility and approved recipients before sharing. Owner-visible metadata may exceed viewer privileges. No raw query text, binds or patient rows are requested.")
    page = st.selectbox("Assessment page", PAGES)
    st.caption("SPEND: measured credits; PERFORMANCE: query spill signals; SECURITY: hierarchy and privileged assignments; OPERATIONS: operational candidates. Units and check IDs are always kept separate.")
    if not st.button("Refresh selected page and coverage"):
        return
    try:
        from snowflake.snowpark.context import get_active_session
        session = get_active_session()
    except Exception:
        st.error("Approved warehouse Snowpark session unavailable. Native execution failed; coverage UNKNOWN.")
        return
    st.subheader("Source coverage")
    display_view(st, session, "V_COVERAGE")
    st.subheader(page.title())
    display_view(st, session, f"V_DASHBOARD_{page}")
    st.caption("Validate source coverage before interpreting any candidate. Read docs/best-practices-guide.md for check-specific evidence, owner validation and remediation.")


if __name__ == "__main__":
    main()
