﻿import streamlit as st
import os
import json
import base64
import importlib.util

# Настройка страницы
st.set_page_config(page_title="CorpHub", page_icon="🏢", layout="wide")

# ==========================================
# УМНОЕ КЭШИРОВАНИЕ ДЛЯ УСКОРЕНИЯ РАБОТЫ
# ==========================================
@st.cache_data(show_spinner=False)
def get_image_base64(image_path, mtime):
    with open(image_path, "rb") as f:
        return base64.b64encode(f.read()).decode()

@st.cache_resource(show_spinner=False)
def load_plugin_module(script_path, mtime):
    spec = importlib.util.spec_from_file_location("plugin_module", script_path)
    plugin_module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(plugin_module)
    return plugin_module

# ==========================================
# CSS ДЛЯ КАРТОЧЕК
# ==========================================
st.markdown("""
<style>
a.custom-card-link {
    text-decoration: none !important;
    color: inherit !important;
    display: block;
    margin-bottom: 16px;
}
.custom-card {
    border: 1px solid rgba(128, 128, 128, 0.2);
    border-radius: 8px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    background-color: transparent;
    transition: all 0.2s ease;
    height: 120px;
}
.custom-card:hover {
    border-color: #0055ff;
    box-shadow: 0 4px 12px rgba(0, 85, 255, 0.15);
    transform: translateY(-2px);
}
.custom-icon {
    font-size: 42px;
    margin-right: 16px;
    width: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.custom-text {
    flex-grow: 1;
    overflow: hidden;
}
.custom-title {
    font-weight: 700;
    font-size: 16px;
    margin-bottom: 4px;
    color: var(--text-color); 
}
.custom-desc {
    font-size: 13px;
    color: var(--text-color); 
    opacity: 0.65; 
    line-height: 1.3;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
.custom-arrow {
    font-size: 18px;
    color: var(--text-color);
    opacity: 0.3;
    margin-left: 8px;
    transition: all 0.2s ease;
}
.custom-card:hover .custom-arrow {
    color: #0055ff;
    opacity: 1;
}
</style>
""", unsafe_allow_html=True)

# ==========================================
# УМНАЯ НАВИГАЦИЯ
# ==========================================
current_page = st.query_params.get("page", "main")

def go_to(page_name):
    st.query_params.page = page_name

# ==========================================
# УНИВЕРСАЛЬНЫЙ СКАНЕР ПАПОК
# ==========================================
def load_category(category_name):
    items = []
    if not os.path.exists(category_name):
        os.makedirs(category_name)
        
    for folder_name in os.listdir(category_name):
        folder_path = os.path.join(category_name, folder_name)
        info_path = os.path.join(folder_path, "info.json")
        
        if os.path.exists(info_path):
            with open(info_path, "r", encoding="utf-8-sig") as f:
                info = json.load(f)
                info["folder_name"] = folder_name
                info["folder_path"] = folder_path
                info["category"] = category_name
                
                icon_file = info.get("icon_file")
                if icon_file:
                    info["icon_path"] = os.path.join(folder_path, icon_file)
                
                # Если это скрипт - ищем script.py
                if category_name == "helpers":
                    script_path = os.path.join(folder_path, "script.py")
                    if os.path.exists(script_path):
                        info["script_path"] = script_path
                        items.append(info)
                        
                # Если это полезное - ищем файл для скачивания
                elif category_name == "useful":
                    download_file = info.get("download_file")
                    if download_file:
                        info["download_path"] = os.path.join(folder_path, download_file)
                        items.append(info)
    return items

helpers_items = load_category("helpers")
useful_items = load_category("useful")
all_plugins = helpers_items + useful_items

# ==========================================
# ФУНКЦИЯ ОТРИСОВКИ HTML-КАРТОЧКИ
# ==========================================
def draw_card(title, description, icon_path=None, icon_emoji="🧩", target_page=None):
    icon_html = f"<div>{icon_emoji}</div>"
    if icon_path and os.path.exists(icon_path):
        mtime = os.path.getmtime(icon_path)
        encoded = get_image_base64(icon_path, mtime)
        ext = icon_path.split('.')[-1]
        icon_html = f"<img src='data:image/{ext};base64,{encoded}' style='max-width: 56px; max-height: 56px;'>"

    href = f"?page={target_page}"
    html = f"""
    <a href="{href}" target="_self" class="custom-card-link">
        <div class="custom-card">
            <div class="custom-icon">{icon_html}</div>
            <div class="custom-text">
                <div class="custom-title">{title}</div>
                <div class="custom-desc">{description}</div>
            </div>
            <div class="custom-arrow">❯</div>
        </div>
    </a>
    """
    st.markdown(html, unsafe_allow_html=True)


# ==========================================
# РОУТИНГ СТРАНИЦ
# ==========================================
if current_page == 'main':
    _, center_col, _ = st.columns([1, 2, 1])
    with center_col:
        st.title("Главное меню")
        st.write("")
        draw_card("Помощники", "Скрипты для работы с Excel, PDF и базами", icon_emoji="🛠", target_page="helpers")
        draw_card("Полезное", "Мессенджер, VPN и другой корпоративный софт", icon_emoji="📁", target_page="useful")

elif current_page == 'helpers':
    st.button("⬅ Назад", on_click=go_to, args=('main',))
    st.title("🛠 Помощники")
    st.write("Скрипты для автоматизации рутины.")
    st.write("---")
    
    _, c1, c2, c3, _ = st.columns([1, 3, 3, 3, 1])
    columns = [c1, c2, c3]
    for index, plugin in enumerate(helpers_items):
        with columns[index % 3]:
            draw_card(plugin.get('title', ''), plugin.get('description', ''), plugin.get('icon_path'), plugin.get('icon', '⚙️'), plugin['folder_name'])

elif current_page == 'useful':
    st.button("⬅ Назад", on_click=go_to, args=('main',))
    st.title("📁 Полезное")
    st.write("Корпоративные программы и инструкции.")
    st.write("---")
    
    _, c1, c2, c3, _ = st.columns([1, 3, 3, 3, 1])
    columns = [c1, c2, c3]
    for index, item in enumerate(useful_items):
        with columns[index % 3]:
            draw_card(item.get('title', ''), item.get('description', ''), item.get('icon_path'), item.get('icon', '💾'), item['folder_name'])

# ==========================================
# ЗАПУСК ВЫБРАННОГО СКРИПТА ИЛИ СТРАНИЦЫ СКАЧИВАНИЯ
# ==========================================
elif any(p["folder_name"] == current_page for p in all_plugins):
    
    plugin = next(p for p in all_plugins if p["folder_name"] == current_page)
    
    # Кнопка возврата ведет в ту категорию, откуда мы пришли
    back_target = plugin["category"]
    st.button("⬅ Назад к списку", on_click=go_to, args=(back_target,))
    
    _, center_col, _ = st.columns([1, 3, 1])
    with center_col:
        # 1. ЗАГОЛОВОК И ОПИСАНИЕ (Поддерживает Markdown)
        st.title(f"{plugin.get('icon', '🧩')} {plugin.get('title', 'Без названия')}")
        if plugin.get("full_description"):
            # Выводим описание как Markdown (можно использовать жирный текст, ссылки и т.д.)
            st.markdown(plugin.get("full_description"))
            st.write("") # Небольшой отступ
            
        # 2. РАБОЧАЯ ЗОНА (Скрипт ИЛИ Скачивание)
        if plugin["category"] == "helpers":
            script_path = plugin["script_path"]
            mtime = os.path.getmtime(script_path)
            plugin_module = load_plugin_module(script_path, mtime)
            plugin_module.run(plugin)
            
        elif plugin["category"] == "useful":
            dl_path = plugin["download_path"]
            if os.path.exists(dl_path):
                with open(dl_path, "rb") as f:
                    st.download_button(
                        label=f"💾 Скачать {plugin.get('download_file')}",
                        data=f,
                        file_name=plugin.get("download_file"),
                        type="primary",
                        use_container_width=True
                    )
            else:
                st.error(f"❌ Файл `{plugin.get('download_file')}` не найден в папке.")
        
        # 3. ОТРИСОВКА ИНСТРУКЦИЙ (СТРОГО НИЖЕ, ОБЩАЯ ДЛЯ ВСЕХ)
        instruction_blocks = []
        for key, value in plugin.items():
            if key.startswith("block_"):
                try:
                    num = int(key.split("_")[1])
                except ValueError:
                    num = 999
                instruction_blocks.append((num, value))

        instruction_blocks.sort(key=lambda x: x[0])

        if instruction_blocks:
            st.write("---")
            st.markdown("### 📖 Дополнительная информация")
            
            for _, block_content in instruction_blocks:
                with st.container(border=True):
                    if isinstance(block_content, dict):
                        text = block_content.get("text", "")
                        image = block_content.get("image", None)
                        
                        if image:
                            img_path = os.path.join(plugin["folder_path"], image)
                            if os.path.exists(img_path):
                                col_text, col_img = st.columns([3, 2], vertical_alignment="center")
                                with col_text:
                                    st.markdown(text)
                                with col_img:
                                    st.image(img_path, use_container_width=True)
                            else:
                                st.markdown(text)
                        else:
                            st.markdown(text)
                            
                    elif isinstance(block_content, str):
                        st.markdown(block_content)