"""
app.py
- Main entry point — YT Analyzer Pro
- With BYOK (Bring Your Own Keys) support
"""

# =====================================================
# NumPy import (safe for both NumPy 1.x and 2.x)
# =====================================================
try:
    import numpy as np
    import numpy._core.multiarray  # noqa
    import numpy._core._multiarray_umath  # noqa
except ImportError:
    try:
        import numpy.core.multiarray  # noqa
        import numpy.core._multiarray_umath  # noqa
    except ImportError:
        pass

import os
import streamlit as st
from core.license import verify_license, save_license, load_license, clear_license
from core.usage_limiter import get_usage, LIMITS

# ===== UI Pages =====
from ui.dashboard_page import render_dashboard
from ui.upload_page import render_upload
from ui.keywords_page import render_keywords
from ui.trending_page import render_trending
from ui.analyze_page import render_analyze
from ui.compare_page import render_compare
from ui.channel_page import render_channel
from ui.competitor_page import render_competitor
from ui.history_page import render_history
from ui.settings_page import render_settings


# =====================================================
# Page Config
# =====================================================
st.set_page_config(
    page_title="YT Analyzer Pro",
    page_icon="🎬",
    layout="wide",
    initial_sidebar_state="expanded",
)


# =====================================================
# Styles
# =====================================================
st.markdown("""
<style>
    .main-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 1.5rem;
        border-radius: 12px;
        color: white;
        text-align: center;
        margin-bottom: 1.5rem;
    }
    .main-header h1 { margin: 0; }
    .stButton>button {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border: none;
        padding: 0.6rem 2rem;
        border-radius: 8px;
        font-weight: 600;
        transition: all 0.2s;
    }
    .stButton>button:hover {
        opacity: 0.9;
        transform: translateY(-1px);
    }
    .stTabs [data-baseweb="tab-list"] button { font-weight: 600; }
    [data-testid="stMetricValue"] {
        color: #667eea;
        font-weight: 700;
    }
    .usage-bar {
        background: rgba(102, 126, 234, 0.1);
        border-left: 3px solid #667eea;
        padding: 6px 10px;
        margin: 4px 0;
        border-radius: 4px;
        font-size: 0.85rem;
    }
    .usage-warning {
        background: rgba(255, 193, 7, 0.15);
        border-left: 3px solid #ffc107;
    }
    .usage-danger {
        background: rgba(244, 67, 54, 0.15);
        border-left: 3px solid #f44336;
    }
</style>
""", unsafe_allow_html=True)


# =====================================================
# Menu
# =====================================================
MENU_OPTIONS = [
    "🏠 Dashboard",
    "📥 Analyze Video (URL)",
    "🔑 Trending Keywords",
    "🔥 Trending Videos",
    "🧠 Video Analyzer (AI)",
    "⚖️ Compare Videos",
    "📈 Channel Analyzer",
    "🕵️ Competitor Spy",
    "📚 History",
    "⚙️ Settings",
]

if "menu" not in st.session_state:
    st.session_state.menu = MENU_OPTIONS[0]

# ⭐ NEW: Settings version (for widget refresh)
if "settings_version" not in st.session_state:
    st.session_state.settings_version = 0


# =====================================================
# License Check
# =====================================================
if "license_ok" not in st.session_state:
    st.session_state.license_ok = False
    st.session_state.license_key = ""
    st.session_state.license_info = {}

    saved = load_license()
    if saved:
        result = verify_license(saved)
        if result["valid"]:
            st.session_state.license_ok = True
            st.session_state.license_key = saved
            st.session_state.license_info = result


# =====================================================
# Login Screen
# =====================================================
if not st.session_state.license_ok:
    st.markdown(
        '<div class="main-header"><h1>🎬 YT Analyzer Pro</h1>'
        '<p>AI-Powered YouTube Video Analysis</p></div>',
        unsafe_allow_html=True,
    )

    _, mid, _ = st.columns([1, 2, 1])
    with mid:
        st.subheader("🔐 Enter License Key")

        key = st.text_input(
            "License Key",
            type="password",
            placeholder="YTK-PRO-XXXX-YYYYMMDD-XXXXXXXX",
            key="login_key_input",
        )

        if st.button("Verify", use_container_width=True, key="login_btn"):
            res = verify_license(key)
            if res["valid"]:
                save_license(key)
                st.session_state.license_ok = True
                st.session_state.license_key = key.strip().upper()
                st.session_state.license_info = res
                st.rerun()
            else:
                st.error(res["message"])

        st.markdown("---")

        with st.expander("❓ Don't have a License Key?", expanded=False):
            admin_user = os.getenv("ADMIN_USERNAME", "ytkeys_admin")
            st.markdown(f"""
### 🔑 Get Your License

**Step 1** — Open Telegram: **[@ytkeys_bot](https://t.me/ytkeys_bot)**

**Step 2** — Send `/start` to the bot

**Step 3** — Choose a plan (TRIAL / PRO / VIP)

**Step 4** — Pay + send screenshot to admin

**Step 5** — Admin sends you a **License Key** (`YTK-PRO-XXXX-YYYYMMDD-XXXXXXXX`)

**Step 6** — Copy that key → paste it above ☝️

---

**📞 Contact admin:** @{admin_user}
            """)

    st.stop()


# =====================================================
# Main App
# =====================================================
st.markdown(
    '<div class="main-header"><h1>🎬 YT Analyzer Pro</h1></div>',
    unsafe_allow_html=True,
)


# =====================================================
# Sidebar
# =====================================================
with st.sidebar:
    info = st.session_state.license_info

    plan = info.get("plan", "Pro")
    days_left = info.get("days_left", 0)
    st.success(f"✅ {plan} Plan")
    if days_left:
        st.caption(f"📅 {days_left} days left")

    hwid = info.get("hwid", "—")
    st.caption(f"HWID: `{hwid}`")

    # ⭐ API Keys Status
    try:
        from core.user_keys import has_user_keys, get_effective_keys
        eff = get_effective_keys()
        if has_user_keys():
            st.success("🔑 Your API Keys Active")
            st.caption("✅ Unlimited usage")
        else:
            yt_count = len(eff.get("youtube_keys", []))
            gm_count = len(eff.get("gemini_keys", []))
            st.caption(f"🔑 Server Keys ({yt_count}YT + {gm_count}GM)")
    except Exception:
        pass

    st.markdown("---")

    menu = st.radio("Menu", MENU_OPTIONS, key="menu")

    st.divider()

    # ===== Usage Limits =====
    with st.expander("📊 Daily Usage", expanded=False):
        try:
            from core.user_keys import has_user_keys
            if has_user_keys():
                st.success("✅ **UNLIMITED** (Your keys)")
            else:
                usage = get_usage()

                groups = {
                    "🧠 AI Features": ["video_analyzer", "compare_videos"],
                    "📈 Analytics": ["channel_analyzer", "competitor_spy"],
                    "🔑 Research": ["trending_keywords", "trending_videos"],
                }

                for group_name, features in groups.items():
                    st.markdown(f"**{group_name}**")
                    for feat in features:
                        u = usage.get(feat)
                        if not u:
                            continue
                        used = u["used"]
                        limit = u["limit"]
                        remaining = u["remaining"]
                        label = u["label"]

                        ratio = used / limit if limit else 0
                        if ratio >= 1:
                            css_class = "usage-danger"
                            icon = "🚫"
                        elif ratio >= 0.7:
                            css_class = "usage-warning"
                            icon = "⚠️"
                        else:
                            css_class = ""
                            icon = ""

                        st.markdown(
                            f'<div class="usage-bar {css_class}">'
                            f'{label} {icon}<br>'
                            f'<b>{used}</b> / {limit} used · '
                            f'<b>{remaining}</b> left'
                            f'</div>',
                            unsafe_allow_html=True,
                        )

                st.caption("🔄 Resets daily at midnight")
                st.caption("💡 Add your keys in ⚙️ Settings → Unlimited")
        except Exception:
            pass

    st.divider()

    # ===== Buttons =====
    col_a, col_b = st.columns(2)
    with col_a:
        if st.button("🔄 Refresh", use_container_width=True, key="btn_refresh"):
            st.cache_data.clear()
            st.rerun()
    with col_b:
        if st.button("🚪 Logout", use_container_width=True, key="btn_logout"):
            clear_license()
            st.session_state.license_ok = False
            st.session_state.license_key = ""
            st.session_state.menu = MENU_OPTIONS[0]
            st.rerun()

    st.caption("Version 1.0.0")


# =====================================================
# Routing
# =====================================================
if menu == "🏠 Dashboard":
    render_dashboard()
elif menu == "📥 Analyze Video (URL)":
    render_upload()
elif menu == "🔑 Trending Keywords":
    render_keywords()
elif menu == "🔥 Trending Videos":
    render_trending()
elif menu == "🧠 Video Analyzer (AI)":
    render_analyze()
elif menu == "⚖️ Compare Videos":
    render_compare()
elif menu == "📈 Channel Analyzer":
    render_channel()
elif menu == "🕵️ Competitor Spy":
    render_competitor()
elif menu == "📚 History":
    render_history()
elif menu == "⚙️ Settings":
    render_settings()