import gradio as gr
from apscheduler.schedulers.background import BackgroundScheduler
from huggingface_hub import snapshot_download

from src.about import (
    INTRODUCTION_TEXT,
    TITLE,
)
from src.display.css_html_js import custom_css
from src.display.utils import (
    AutoEvalColumn,
    fields,
)
from src.envs import API, EVAL_RESULTS_PATH, REPO_ID, RESULTS_REPO, TOKEN
from src.populate import get_new_leaderboard_df


def restart_space():
    API.restart_space(repo_id=REPO_ID)

try:
    print(EVAL_RESULTS_PATH)
    snapshot_download(
        repo_id=RESULTS_REPO, local_dir=EVAL_RESULTS_PATH, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN
    )
except Exception:
    restart_space()

original_df = get_new_leaderboard_df(EVAL_RESULTS_PATH)
leaderboard_df = original_df.copy()

demo = gr.Blocks(css=custom_css)
with demo:
    gr.HTML(TITLE)
    gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")

    with gr.Tabs(elem_classes="tab-buttons") as tabs:
        with gr.TabItem("🏅 System", elem_id="llm-benchmark-tab-table", id=0):
            leaderboard_table = gr.components.Dataframe(
                value=[leaderboard_df.iloc[idx] for idx in range(len(leaderboard_df))],
                headers=[c.name for c in fields(AutoEvalColumn)],
                datatype=[c.type for c in fields(AutoEvalColumn)],
                elem_id="leaderboard-table",
                interactive=False,
                visible=True,
            )

scheduler = BackgroundScheduler()
scheduler.add_job(restart_space, "interval", seconds=1800)
scheduler.start()
demo.queue(default_concurrency_limit=40).launch()