import streamlit as st
from huggingface_hub import HfApi, create_repo, upload_file
import os
import requests
import json

# Set up Google API key
google_api_key = st.secrets["googleapi"]
google_api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={google_api_key}"

# App title
st.title("HF DevAssist - Create and Manage Hugging Face Spaces")

# Input for Hugging Face token
if "hf_token" not in st.session_state:
    st.session_state["hf_token"] = None

st.subheader("Authenticate with Hugging Face")
if st.session_state["hf_token"] is None:
    token_input = st.text_input("Enter your Hugging Face Access Token:", type="password")
    if token_input:
        st.session_state["hf_token"] = token_input
        st.success("Token saved.")
else:
    st.write("Token already saved.")

if st.session_state["hf_token"] is None:
    st.error("Please provide a valid Hugging Face token to proceed.")
    st.stop()

hf_api_key = st.session_state["hf_token"]

# Authenticate Hugging Face API
api = HfApi()
try:
    user_info = api.whoami(token=hf_api_key)
    st.success(f"Authenticated as {user_info['name']}")
except Exception as e:
    st.error(f"Authentication failed: {e}")
    st.stop()

# User Input for Space creation
st.subheader("Describe Your App")
space_name = st.text_input("Enter the name for the new or existing Hugging Face Space:")
app_description = st.text_area("Describe the app you want to create:", height=150)

if st.button("Generate and Deploy App"):
    if not space_name.strip():
        st.error("Space name cannot be empty.")
    elif not app_description.strip():
        st.error("App description cannot be empty.")
    else:
        try:
            # Generate app code using Google API
            st.info("Generating app code using Google API...")
            payload = {
                "contents": [
                    {
                        "parts": [{"text": f"Generate a Streamlit app with the following description: {app_description}. Include the app code followed by '### requirements.txt' and the dependencies required."}]
                    }
                ]
            }
            headers = {"Content-Type": "application/json"}
            response = requests.post(google_api_url, headers=headers, json=payload)

            if response.status_code != 200:
                st.error(f"Google API request failed with status code {response.status_code}: {response.text}")
                st.stop()

            generated_code = response.json()["contents"][0]["parts"][0]["text"]
            st.text_area("Debug: Google API Response", generated_code, height=150)

            # Split generated code
            try:
                app_code, req_code = generated_code.split("### requirements.txt")
                app_code = app_code.strip()
                req_code = req_code.strip()
            except ValueError:
                st.error("The Google API response did not contain the expected sections. Please try again.")
                st.stop()

            # Create or update Hugging Face Space
            space_full_name = f"{user_info['name']}/{space_name}"
            try:
                st.info(f"Checking if Space '{space_full_name}' exists...")
                api.repo_info(repo_id=space_full_name, repo_type="space", token=hf_api_key)
                st.success(f"Space '{space_full_name}' exists. Updating files...")
            except:
                st.info(f"Space '{space_full_name}' does not exist. Creating new Space...")
                create_repo(repo_id=space_name, repo_type="space", space_sdk="streamlit", token=hf_api_key)

            # Upload `app.py`
            with open("app.py", "w") as app_file:
                app_file.write(app_code)
            upload_file(
                path_or_fileobj="app.py",
                path_in_repo="app.py",
                repo_id=space_full_name,
                repo_type="space",
                token=hf_api_key,
            )

            # Upload `requirements.txt`
            with open("requirements.txt", "w") as req_file:
                req_file.write(req_code)
            upload_file(
                path_or_fileobj="requirements.txt",
                path_in_repo="requirements.txt",
                repo_id=space_full_name,
                repo_type="space",
                token=hf_api_key,
            )

            st.success(f"App successfully deployed in Space '{space_full_name}'!")

        except Exception as e:
            st.error(f"An error occurred: {e}")
        finally:
            # Clean up temporary files
            if os.path.exists("app.py"):
                os.remove("app.py")
            if os.path.exists("requirements.txt"):
                os.remove("requirements.txt")