import gradio as gr
import json
import os

class JSONEditor:
    def __init__(self):
        self.current_data = None
        self.current_filename = None

    def load_json(self, file):
        """Load JSON file and return its contents"""
        try:
            # Use filepath instead of file object
            with open(file, 'r', encoding='utf-8') as f:
                data = json.load(f)
            self.current_data = data
            self.current_filename = os.path.basename(file)
            return json.dumps(data, indent=2), f"Successfully loaded {self.current_filename}"
        except Exception as e:
            return "", f"Error loading file: {str(e)}"

    def update_json(self, json_str):
        """Validate and update JSON data"""
        try:
            # Validate JSON
            updated_data = json.loads(json_str)
            self.current_data = updated_data
            return json.dumps(updated_data, indent=2), "JSON updated successfully"
        except json.JSONDecodeError as e:
            return json_str, f"Invalid JSON: {str(e)}"

    def save_json(self):
        """Save current JSON data to a file"""
        if not self.current_data:
            return "No data to save", None

        try:
            # Create a default filename if not already loaded from a file
            save_filename = self.current_filename or "edited_data.json"
            
            # Ensure the file is saved in the current working directory
            save_path = os.path.join(os.getcwd(), save_filename)
            
            with open(save_path, 'w', encoding='utf-8') as f:
                json.dump(self.current_data, f, indent=2)
            
            return f"File saved as {save_filename}", save_path
        except Exception as e:
            return f"Error saving file: {str(e)}", None

# Create an instance of JSONEditor
json_editor = JSONEditor()

def create_interface():
    """Create Gradio interface"""
    with gr.Blocks() as demo:
        # File upload component - changed to filepath
        file_input = gr.File(file_count="single", type="filepath", 
                             file_types=['.json'], 
                             label="Upload JSON File")
        
        # Status message area
        status_output = gr.Textbox(label="Status", interactive=False)
        
        # JSON text area for editing
        json_text = gr.Textbox(label="JSON Content", 
                                lines=20, 
                                interactive=True)
        
        # Buttons for actions
        with gr.Row():
            load_btn = gr.Button("Load File")
            update_btn = gr.Button("Update JSON")
            save_btn = gr.Button("Save File")
        
        # File download component
        file_output = gr.File(label="Download Edited JSON")
        
        # Event handlers
        load_btn.click(
            fn=json_editor.load_json, 
            inputs=file_input, 
            outputs=[json_text, status_output]
        )
        
        update_btn.click(
            fn=json_editor.update_json, 
            inputs=json_text, 
            outputs=[json_text, status_output]
        )
        
        save_btn.click(
            fn=json_editor.save_json, 
            inputs=None, 
            outputs=[status_output, file_output]
        )
    
    return demo

# Launch the Gradio app
if __name__ == "__main__":
    interface = create_interface()
    interface.launch(server_name="0.0.0.0", server_port=7860)

# Requirements for Hugging Face Spaces:
# - gradio
# - Requirements file would look like:
# gradio>=3.50.0

"""
Hugging Face Spaces Deployment Instructions:
1. Create a new Space
2. Choose Python as the SDK
3. Select Gradio as the Space SDK
4. Upload this script as app.py
5. Create a requirements.txt with the gradio dependency
6. Make sure to set the Space visibility as you prefer

Recommended Space Configuration:
- Hardware: CPU Basic
- Space SDK: Gradio
- Python Version: 3.10+
"""