import gradio as gr
import requests
from huggingface_hub import whoami
from huggingface_hub.utils import build_hf_headers, hf_raise_for_status
from gradio_huggingfacehub_search import HuggingfaceHubSearch

ENDPOINT = "https://huggingface.co"
# ENDPOINT = "http://localhost:5564"

REPO_TYPES = ["model", "dataset", "space"]


def duplicate(source_repo, dst_repo, repo_type, private, oauth_token: gr.OAuthToken | None):
    print(oauth_token.token)
    try:
        if not repo_type in REPO_TYPES:
            raise ValueError("need to select valid repo type")
        _ = whoami(oauth_token.token)
        # ^ this will throw if token is invalid

        r = requests.post(
            f"{ENDPOINT}/api/{repo_type}s/{source_repo}/duplicate",
            headers=build_hf_headers(token=oauth_token.token),
            json={"repository": dst_repo, "private": private},
        )
        hf_raise_for_status(r)

        repo_url = r.json().get("url")

        return (
            f'Find your repo <a href=\'{repo_url}\' target="_blank" style="text-decoration:underline">here</a>',
            "sp.jpg",
        )

    except Exception as e:
        raise gr.Error(f"""Oops, you forgot to login. Please use the loggin button on the top left to migrate your repo {e}""")

interface = gr.Interface(
    fn=duplicate,
    inputs=[
        HuggingfaceHubSearch(
            placeholder="Source repository (e.g. osanseviero/src)",
            search_type=["model", "dataset", "space"],
            sumbit_on_select=False,
        ),
        gr.Textbox(placeholder="Destination repository (e.g. osanseviero/dst)"),
        gr.Dropdown(choices=REPO_TYPES, value="model"),
        gr.Checkbox(label="Make new repo private?"),
    ],
    outputs=[
        gr.Markdown(label="output"),
        gr.Image(show_label=False),
    ],
    title="Duplicate your repo!",
    description="Duplicate a Hugging Face repository! You need to specify a write token obtained in https://hf.co/settings/tokens. This Space is a an experimental demo.",
    article="<p>Find your write token at <a href='https://huggingface.co/settings/tokens' target='_blank'>token settings</a></p>",
    allow_flagging="never",
    live=False
)

def swap_visibilty(profile: gr.OAuthProfile | None):
    return gr.update(elem_classes=["main_ui_logged_in"]) if profile else gr.update(elem_classes=["main_ui_logged_out"])
        
css = '''
.main_ui_logged_out{opacity: 0.3; pointer-events: none}
'''
with gr.Blocks(css=css) as demo:
    gr.LoginButton()
    with gr.Column(elem_classes="main_ui_logged_out") as main_ui:
        interface.render()
    demo.load(fn=swap_visibilty, outputs=main_ui)
    
demo.queue()
demo.launch()