import streamlit as st
import sqlite3
import pandas as pd
from datetime import datetime, timedelta

# --- CONFIG & STYLING ---
st.set_page_config(page_title="The Study Chain", layout="wide", initial_sidebar_state="expanded")

# Persistent State for Dark/Light Mode (light is the default)
if 'theme' not in st.session_state:
    st.session_state.theme = 'light'

def toggle_theme():
    st.session_state.theme = 'dark' if st.session_state.theme == 'light' else 'light'

# --- COLORS & TOKENS ---
THEMES = {
    'light': {
        'bg': '#ffffff',
        'text': '#1a1a1a',
        'muted': '#666666',
        'border': '#eeeeee',
        'card_bg': '#fafafa',
        'accent': '#000000',
        'tag_bg': '#f0f0f0',
        'tag_text': '#444444',
        'table_bg': '#ffffff',
        'table_header_bg': '#f5f5f5',
        'table_text': '#1a1a1a'
    },
    'dark': {
        'bg': '#121212',
        'text': '#eeeeee',
        'muted': '#aaaaaa',
        'border': '#333333',
        'card_bg': '#1e1e1e',
        'accent': '#ffffff',
        'tag_bg': '#2d2d2d',
        'tag_text': '#cccccc',
        'table_bg': '#1e1e1e',
        'table_header_bg': '#2d2d2d',
        'table_text': '#eeeeee'
    }
}

t = THEMES[st.session_state.theme]

# Category Colors
CATEGORY_COLORS = {
    "Logic": {"bg": "#1565c0", "text": "#ffffff"},
    "Legal theory": {"bg": "#7b1fa2", "text": "#ffffff"},
    "Theology": {"bg": "#e65100", "text": "#ffffff"},
    "Philosophy": {"bg": "#2e7d32", "text": "#ffffff"},
    "Mysticism": {"bg": "#c2185b", "text": "#ffffff"},
    "Exegesis": {"bg": "#00695c", "text": "#ffffff"}
}

def get_category_style(name):
    for cat, style in CATEGORY_COLORS.items():
        if cat.lower() in name.lower():
            return style
    return {"bg": t['tag_bg'], "text": t['tag_text']}

st.markdown(f"""
<style>
    @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono&display=swap');

    /* Hide Streamlit default chrome: header, footer, deploy/menu button */
    #MainMenu {{ visibility: hidden !important; }}
    header[data-testid="stHeader"] {{ display: none !important; }}
    footer {{ visibility: hidden !important; display: none !important; }}
    div[data-testid="stToolbar"] {{ display: none !important; }}
    div[data-testid="stDecoration"] {{ display: none !important; }}
    .stDeployButton {{ display: none !important; }}

    .stApp {{
        background-color: {t['bg']} !important;
        color: {t['text']} !important;
    }}

    .main {{
        background-color: {t['bg']} !important;
        color: {t['text']} !important;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important;
    }}

    /* Force a serif display face for all titles and headers */
    h1, h2, h3, .phase-title, .card-title {{
        font-family: "Exposure", Georgia, "Times New Roman", Times, serif !important;
        font-weight: 700 !important;
        letter-spacing: -0.02em !important;
        color: {t['text']} !important;
    }}

    .header-section {{
        text-align: center !important;
        padding: 4rem 0 2rem 0 !important;
    }}

    .header-subtitle {{
        color: {t['muted']} !important;
        text-transform: uppercase !important;
        font-size: 0.8rem !important;
        letter-spacing: 0.1em !important;
        margin-bottom: 0.5rem !important;
    }}

    .stats-bar {{
        display: flex !important;
        justify-content: center !important;
        gap: 3rem !important;
        padding: 2rem 0 !important;
        border-top: 1px solid {t['border']} !important;
        border-bottom: 1px solid {t['border']} !important;
        margin-bottom: 3rem !important;
        flex-wrap: wrap !important;
    }}

    .stat-item {{
        text-align: center !important;
    }}

    .stat-value {{
        font-size: 1.5rem !important;
        font-weight: 700 !important;
        display: block !important;
        color: {t['text']} !important;
    }}

    .stat-label {{
        font-size: 0.75rem !important;
        color: {t['muted']} !important;
        text-transform: uppercase !important;
        letter-spacing: 0.05em !important;
    }}

    .phase-header {{
        margin-top: 4rem !important;
        margin-bottom: 1rem !important;
        display: flex !important;
        align-items: baseline !important;
        gap: 1rem !important;
    }}

    .phase-number {{
        font-family: 'JetBrains Mono', monospace !important;
        font-size: 1.2rem !important;
        color: {t['muted']} !important;
    }}

    .phase-title {{
        font-size: 1.8rem !important;
        color: {t['text']} !important;
    }}

    .subject-card {{
        background: {t['card_bg']} !important;
        border: 1px solid {t['border']} !important;
        border-radius: 12px !important;
        padding: 2rem !important;
        height: 100% !important;
        display: flex !important;
        flex-direction: column !important;
        justify-content: space-between !important;
        transition: all 0.2s ease !important;
    }}

    .subject-card:hover {{
        border-color: {t['accent']} !important;
        transform: translateY(-2px) !important;
        box-shadow: 0 4px 12px rgba(0,0,0,0.05) !important;
    }}

    .card-tag {{
        display: inline-block !important;
        padding: 3px 10px !important;
        border-radius: 4px !important;
        font-size: 0.7rem !important;
        font-weight: 700 !important;
        text-transform: uppercase !important;
        letter-spacing: 0.05em !important;
        margin-bottom: 0.75rem !important;
    }}

    .card-title {{
        font-size: 1.2rem !important;
        font-weight: 700 !important;
        margin-bottom: 0.75rem !important;
        line-height: 1.3 !important;
        color: {t['text']} !important;
    }}

    .card-meta {{
        font-size: 0.85rem !important;
        color: {t['muted']} !important;
        margin-bottom: 1.25rem !important;
        font-family: 'JetBrains Mono', monospace !important;
    }}

    .progress-container {{
        height: 8px !important;
        background: {t['border']} !important;
        border-radius: 4px !important;
        overflow: hidden !important;
    }}

    .progress-fill {{
        height: 100% !important;
        background: {t['accent']} !important;
        border-radius: 4px !important;
    }}

    .progress-text {{
        font-size: 0.75rem !important;
        font-weight: 600 !important;
        margin-top: 0.5rem !important;
        display: block !important;
        color: {t['text']} !important;
    }}

    /* Streamlit Overrides */
    .stRadio [role="radiogroup"] {{
        flex-direction: row !important;
        gap: 1rem !important;
    }}

    div[data-testid="stSidebar"] {{
        background-color: {t['card_bg']} !important;
        border-right: 1px solid {t['border']} !important;
    }}

    /* Force theme onto Streamlit's built-in dataframes and tables */
    div[data-testid="stDataFrame"],
    div[data-testid="stTable"] {{
        background-color: {t['table_bg']} !important;
        color: {t['table_text']} !important;
        border: 1px solid {t['border']} !important;
        border-radius: 8px !important;
    }}

    div[data-testid="stDataFrame"] *,
    div[data-testid="stTable"] * {{
        color: {t['table_text']} !important;
        border-color: {t['border']} !important;
    }}

    div[data-testid="stTable"] table,
    div[data-testid="stTable"] tbody tr,
    div[data-testid="stTable"] td {{
        background-color: {t['table_bg']} !important;
    }}

    div[data-testid="stTable"] thead tr th,
    div[data-testid="stDataFrame"] thead tr th {{
        background-color: {t['table_header_bg']} !important;
        color: {t['table_text']} !important;
        font-weight: 700 !important;
    }}

    /* Glide data-editor canvas backdrop used by stDataFrame */
    div[data-testid="stDataFrame"] [data-testid="glide-cell"],
    div[data-testid="stDataFrame"] .glideDataEditor {{
        background-color: {t['table_bg']} !important;
        color: {t['table_text']} !important;
    }}
</style>
""", unsafe_allow_html=True)

# --- SIDEBAR CONTROLS ---
with st.sidebar:
    st.title("Controls")
    st.button("Toggle Theme 🌓", on_click=toggle_theme)
    st.divider()
    view_mode = st.radio("View Mode", ["Grid", "Table"])
    show_completed = st.checkbox("Show Completed", value=True)
    st.divider()
    st.subheader("Daily Target")
    lectures_per_day_input = st.slider("Lectures completed per day", 1, 20, 10)

# --- TITLE NORMALIZATION ---
# Clean academic Title Case for every series. Keyed by the legacy lowercase
# label so the dashboard renders correctly even if the database still holds
# old, inconsistently-cased titles.
TITLE_MAP = {
    "from the islam of hadith to the islam of the qur’an": "From the Islam of Hadith to the Islam of the Qur'an",
    "the holy qur’an in the hadith of the messenger of god": "The Holy Qur'an in the Hadith of the Messenger of God",
    "the stations of the chosen one (pbuh)": "The Stations of the Chosen One (PBUH)",
    "imamate in the holy qur’an": "Imamate in the Holy Qur'an",
    "the day of resurrection": "The Day of Resurrection",
    "the greatest messenger in islamic heritage": "The Greatest Messenger in Islamic Heritage",
    "religious authority and the caliphate after the messenger of god": "Religious Authority and the Caliphate After the Messenger of God",
    "features of umayyad islam": "Features of Umayyad Islam",
    "short miscellany": "Short Miscellany",
    "advanced lessons in fiqh": "Advanced Lessons in Fiqh",
    "advanced lessons in usul al-fiqh": "Advanced Lessons in Usul al-Fiqh",
    "lessons in justice": "Lessons in Justice",
    "lessons": "Lessons",
    "lectures": "Lectures",
    "lessons in qur’anic exegesis": "Lessons in Qur'anic Exegesis",
    "the theory of the uprightness of the companions": "The Theory of the Uprightness of the Companions",
    "monotheism / divine unity": "Monotheism / Divine Unity",
    "knowing god": "Knowing God",
    "the afterlife in the holy qur’an": "The Afterlife in the Holy Qur'an",
    "miscellaneous researches": "Miscellaneous Researches",
    "face to face": "Face to Face",
    "qur’anic reflections": "Qur'anic Reflections",
    "qur’anic terminology": "Qur'anic Terminology",
    "monotheism in nahj al-balagha": "Monotheism in Nahj al-Balagha",
    "the mahdist thesis": "The Mahdist Thesis",
    "reflections on modernity and postmodernity": "Reflections on Modernity and Postmodernity",
    "the rule of grace: presentation and critique": "The Rule of Grace: Presentation and Critique",
    "the logic of understanding the husayni uprising": "The Logic of Understanding the Husayni Uprising",
    "debates on the renewal of religious thought": "Debates on the Renewal of Religious Thought",
}

def normalize_title(name):
    if name is None:
        return name
    key = name.strip().lower().replace("'", "’")
    if key in TITLE_MAP:
        return TITLE_MAP[key]
    # Fallback: title-case unknown labels while preserving short connecting words.
    minor = {"the", "of", "in", "to", "and", "a", "an", "for", "on", "after", "al"}
    words = name.split()
    out = []
    for i, w in enumerate(words):
        if i != 0 and i != len(words) - 1 and w.lower() in minor:
            out.append(w.lower())
        else:
            out.append(w[:1].upper() + w[1:] if w else w)
    return " ".join(out)

# --- DATA HELPERS ---
import os

def find_database():
    """Locate lectures.db regardless of the working directory.

    Checks, in order: the current directory, the folder containing this
    script, and the user's home directory (where ingest_real_roster.py
    writes it). Returns the first path that exists, else 'lectures.db'.
    """
    candidates = [
        'lectures.db',
        os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lectures.db'),
        os.path.join(os.path.expanduser('~'), 'lectures.db'),
    ]
    for path in candidates:
        if os.path.exists(path):
            return path
    return 'lectures.db'

def get_db_connection(db_name):
    return sqlite3.connect(db_name)

def load_data():
    try:
        conn = get_db_connection(find_database())
        df = pd.read_sql_query("""
            SELECT s.series_title as series_name, 
                   COUNT(l.lecture_id) as total_lectures,
                   AVG(l.transcription_status) as progress
            FROM series s
            LEFT JOIN lectures l ON s.series_id = l.series_id
            GROUP BY s.series_id
        """, conn)
        conn.close()
        return df
    except Exception:
        return pd.DataFrame()

df_series = load_data()

if not df_series.empty:
    df_series['series_name'] = df_series['series_name'].apply(normalize_title)

def assign_phase(name):
    name = name.lower()
    if any(x in name for x in ['logic', 'mantiq', 'legal theory', 'usul', 'halqa', 'doctrinal', 'aqaid']):
        return 1
    if any(x in name for x in ['philosophy', 'hikma', 'soul', 'kalam', 'rational']):
        return 2
    return 3

if not df_series.empty:
    df_series['phase'] = df_series['series_name'].apply(assign_phase)
    if df_series['series_name'].iloc[0].startswith('Specialized'):
        df_series['phase'] = 1
        df_series.loc[10:20, 'phase'] = 2
        df_series.loc[20:, 'phase'] = 3

# --- HEADER ---
st.markdown(f"""
    <div class="header-section">
        <div class="header-subtitle">Sayyid Kamal al-Haydari · Study chain</div>
        <h1>Curriculum Dashboard</h1>
        <p style="color: {t['muted']}; max-width: 600px; margin: 1rem auto;">A local-first map of the lecture corpus: every series placed in its phase and tracked against transcription progress.</p>
    </div>
""", unsafe_allow_html=True)

# --- STATS BAR ---
if not df_series.empty:
    total_lects = int(df_series['total_lectures'].sum())
    master_prog = df_series['progress'].mean()
    total_subjects = len(df_series)
    
    remaining_lects = total_lects * (1 - master_prog/100)
    days_rem = remaining_lects / (lectures_per_day_input if lectures_per_day_input > 0 else 1)
    eta_date = (datetime.now() + timedelta(days=days_rem)).strftime("%b %Y")

    st.markdown(f"""
        <div class="stats-bar">
            <div class="stat-item">
                <span class="stat-value">3</span>
                <span class="stat-label">phases</span>
            </div>
            <div class="stat-item">
                <span class="stat-value">{total_subjects}</span>
                <span class="stat-label">series</span>
            </div>
            <div class="stat-item">
                <span class="stat-value">{total_lects}</span>
                <span class="stat-label">lectures</span>
            </div>
            <div class="stat-item">
                <span class="stat-value">{master_prog:.1f}%</span>
                <span class="stat-label">studied</span>
            </div>
            <div class="stat-item">
                <span class="stat-value">{eta_date}</span>
                <span class="stat-label">eta</span>
            </div>
        </div>
    """, unsafe_allow_html=True)

# --- PHASES ---
phases = [
    {"num": "01", "title": "Foundations", "desc": "The instrumental sciences: how to reason, how rulings are derived, what the creed asserts.", "id": 1},
    {"num": "02", "title": "Rational Theology", "desc": "Demonstrative reasoning turned on doctrine: kalam, the soul, and the bridge into philosophy.", "id": 2},
    {"num": "03", "title": "Higher Metaphysics", "desc": "Transcendent philosophy, mysticism, and the thematic reading of the Qur'an.", "id": 3}
]

for phase in phases:
    phase_data = df_series[df_series['phase'] == phase['id']]
    if not show_completed:
        phase_data = phase_data[phase_data['progress'] < 100]
    
    if phase_data.empty:
        continue
        
    st.markdown(f"""
        <div class="phase-header">
            <span class="phase-number">{phase['num']}</span>
            <span class="phase-title">{phase['title']}</span>
        </div>
        <p style="color: {t['muted']}; margin-bottom: 2rem;">{phase['desc']}</p>
    """, unsafe_allow_html=True)
    
    if view_mode == "Grid":
        cols = st.columns(3)
        for i, (idx, row) in enumerate(phase_data.iterrows()):
            col_idx = i % 3
            with cols[col_idx]:
                cat_style = get_category_style(row['series_name'])
                st.markdown(f"""
                    <div class="subject-card">
                        <div>
                            <div class="card-tag" style="background: {cat_style['bg']}; color: {cat_style['text']};">
                                {row['series_name'].split()[0] if ' ' in row['series_name'] else row['series_name']}
                            </div>
                            <div class="card-title">{row['series_name']}</div>
                            <div class="card-meta">{int(row['total_lectures'])} lectures</div>
                        </div>
                        <div>
                            <div class="progress-container">
                                <div class="progress-fill" style="width: {row['progress']}%"></div>
                            </div>
                            <span class="progress-text">{row['progress']:.1f}% transcribed</span>
                        </div>
                    </div>
                """, unsafe_allow_html=True)
                st.write("") # Spacer
    else:
        st.dataframe(phase_data[['series_name', 'total_lectures', 'progress']], use_container_width=True)

# --- FOOTER ---
st.markdown(f"""
    <div style="text-align: center; margin-top: 5rem; padding: 2rem; border-top: 1px solid {t['border']}; color: {t['muted']}; font-size: 0.8rem;">
        The Study Chain Dashboard · Built to hold one complex curriculum well.
    </div>
""", unsafe_allow_html=True)
