import os
import gradio as gr
import requests
import inspect
import pandas as pd
import json
import time
import sys
from pathlib import Path

# Fix cookies import by creating a module structure dynamically
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
    sys.path.insert(0, current_dir)

# Create __init__.py file if it doesn't exist
init_path = os.path.join(current_dir, "__init__.py")
if not os.path.exists(init_path):
    with open(init_path, "w") as f:
        f.write("")  # Create empty __init__.py file

# Now imports should work
try:
    from cookies import COOKIES
    # Test the import to ensure it works
    print("Successfully imported COOKIES")
except ImportError as e:
    print(f"Error importing COOKIES: {e}")
    # If import fails, try a direct import with modified sys.modules
    import cookies
    sys.modules[__name__ + '.cookies'] = cookies
    print("Added cookies to sys.modules")

# Now the rest of your imports should work
from dotenv import load_dotenv
from huggingface_hub import login
from text_inspector_tool import TextInspectorTool
from text_web_browser import (
    ArchiveSearchTool,
    FinderTool,
    FindNextTool,
    PageDownTool,
    PageUpTool,
    SimpleTextBrowser,
    VisitTool,
)
from visual_qa import visualizer
from reformulator import prepare_response

from smolagents import (
    CodeAgent,
    GoogleSearchTool,
    LiteLLMModel,
    ToolCallingAgent,
)

# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

# GAIA system prompt for exact answer format
GAIA_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""

# --- Smolagent Implementation ---
load_dotenv(override=True)

# Try to login with HF token from env or secrets
try:
    hf_token = os.getenv("HF_TOKEN")
    if hf_token:
        login(hf_token)
        print("Successfully logged in to Hugging Face")
    else:
        print("No HF_TOKEN found in environment")
except Exception as e:
    print(f"Error logging in to Hugging Face: {e}")

# Custom settings for your agent
custom_role_conversions = {"tool-call": "assistant", "tool-response": "user"}
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"

BROWSER_CONFIG = {
    "viewport_size": 1024 * 5,
    "downloads_folder": "downloads_folder",
    "request_kwargs": {
        "headers": {"User-Agent": user_agent},
        "timeout": 300,
    },
    "serpapi_key": os.getenv("SERPAPI_API_KEY"),
}

# Create downloads folder if it doesn't exist
os.makedirs(f"./{BROWSER_CONFIG['downloads_folder']}", exist_ok=True)

class SmolaAgent:
    def __init__(self):
        print("Initializing SmolaAgent...")
        
        # Initialize model
        model_id = "o1"  # You can adjust this or make it configurable
        model_params = {
            "model_id": model_id,
            "custom_role_conversions": custom_role_conversions,
            "max_completion_tokens": 8192,
        }
        if model_id == "o1":
            model_params["reasoning_effort"] = "high"
        
        self.model = LiteLLMModel(**model_params)
        
        # Create agent with tools
        text_limit = 100000
        browser = SimpleTextBrowser(**BROWSER_CONFIG)
        WEB_TOOLS = [
            GoogleSearchTool(provider="serper"),
            VisitTool(browser),
            PageUpTool(browser),
            PageDownTool(browser),
            FinderTool(browser),
            FindNextTool(browser),
            ArchiveSearchTool(browser),
            TextInspectorTool(self.model, text_limit),
        ]
        
        # Create text webbrowser agent
        self.text_webbrowser_agent = ToolCallingAgent(
            model=self.model,
            tools=WEB_TOOLS,
            max_steps=20,
            verbosity_level=2,
            planning_interval=4,
            name="search_agent",
            description="""A team member that will search the internet to answer your question.
        Ask him for all your questions that require browsing the web.
        Provide him as much context as possible, in particular if you need to search on a specific timeframe!
        And don't hesitate to provide him with a complex search task, like finding a difference between two webpages.
        Your request must be a real sentence, not a google search! Like "Find me this information (...)" rather than a few keywords.
        """,
            provide_run_summary=True,
        )
        
        self.text_webbrowser_agent.prompt_templates["managed_agent"]["task"] += """You can navigate to .txt online files.
        If a non-html page is in another format, especially .pdf or a Youtube video, use tool 'inspect_file_as_text' to inspect it.
        Additionally, if after some searching you find out that you need more information to answer the question, you can use `final_answer` with your request for clarification as argument to request for more information."""

        # Create manager agent
        self.manager_agent = CodeAgent(
            model=self.model,
            tools=[visualizer, TextInspectorTool(self.model, text_limit)],
            max_steps=12,
            verbosity_level=2,
            additional_authorized_imports=["*"],
            planning_interval=4,
            managed_agents=[self.text_webbrowser_agent],
        )
        
        print("SmolaAgent initialized successfully.")

    def __call__(self, question: str) -> str:
        print(f"Agent received question: {question[:50]}...")
        
        # Include the GAIA system prompt in the question to ensure proper answer format
        augmented_question = f"""You have one question to answer. It is paramount that you provide a correct answer.
Give it all you can: I know for a fact that you have access to all the relevant tools to solve it and find the correct answer (the answer does exist). Failure or 'I cannot answer' or 'None found' will not be tolerated, success will be rewarded.
Run verification steps if that's needed, you must make sure you find the correct answer!

{GAIA_SYSTEM_PROMPT}

Here is the task:
{question}"""
        
        try:
            # Run the agent
            result = self.manager_agent.run(augmented_question)
            
            # Use reformulator to get properly formatted final answer
            agent_memory = self.manager_agent.write_memory_to_messages()
            
            # Add the GAIA system prompt to the reformulation to ensure correct format
            for message in agent_memory:
                if message.get("role") == "system" and message.get("content"):
                    if isinstance(message["content"], list):
                        for content_item in message["content"]:
                            if content_item.get("type") == "text":
                                content_item["text"] = GAIA_SYSTEM_PROMPT + "\n\n" + content_item["text"]
                    else:
                        message["content"] = GAIA_SYSTEM_PROMPT + "\n\n" + message["content"]
                    break
            
            final_answer = prepare_response(augmented_question, agent_memory, self.model)
            
            print(f"Agent returning answer: {final_answer}")
            return final_answer
        
        except Exception as e:
            print(f"Error running agent: {e}")
            return "FINAL ANSWER: Unable to determine"

# Function to extract the exact answer from agent response
def extract_final_answer(agent_response):
    if "FINAL ANSWER:" in agent_response:
        answer = agent_response.split("FINAL ANSWER:")[1].strip()
        
        # Additional cleaning to ensure exact match
        # Remove any trailing punctuation
        answer = answer.rstrip('.,!?;:')
        
        # Clean numbers (remove commas and units)
        # This is a simple example - you might need more sophisticated cleaning
        words = answer.split()
        for i, word in enumerate(words):
            # Try to convert to a number to remove commas and format correctly
            try:
                num = float(word.replace(',', '').replace('$', '').replace('%', ''))
                # Convert to int if it's a whole number
                words[i] = str(int(num)) if num.is_integer() else str(num)
            except (ValueError, AttributeError):
                # Not a number, leave as is
                pass
        
        return ' '.join(words)
    
    return "Unable to determine"

# Constants for file paths
QUESTIONS_CACHE_FILE = "cached_questions.json"
ANSWERS_CACHE_FILE = "cached_answers.json"
SUBMISSION_READY_FILE = "submission_ready.json"

def process_questions(profile: gr.OAuthProfile | None):
    """
    Processes all questions using the agent and saves the answers to cache.
    Does not submit the answers.
    """
    # --- Determine HF Space Runtime URL and Repo URL ---
    if profile:
        username = f"{profile.username}"
        print(f"User logged in: {username}")
    else:
        print("User not logged in.")
        return "Please Login to Hugging Face with the button.", None

    # 1. Instantiate Agent
    try:
        agent = SmolaAgent()
    except Exception as e:
        print(f"Error instantiating agent: {e}")
        return f"Error initializing agent: {e}", None

    # 2. Use cached questions only
    if os.path.exists(QUESTIONS_CACHE_FILE) and os.path.getsize(QUESTIONS_CACHE_FILE) > 10:
        print(f"Loading cached questions from {QUESTIONS_CACHE_FILE}")
        try:
            with open(QUESTIONS_CACHE_FILE, 'r') as f:
                questions_data = json.load(f)
            print(f"Loaded {len(questions_data)} questions from cache")
        except Exception as e:
            print(f"Error loading cached questions: {e}")
            return f"Error loading cached questions: {e}", None
    else:
        return "No cached questions found. Please create a cached_questions.json file.", None

    # 3. Run your Agent
    results_log = []
    processed_count = 0
    
    # Try to load cached answers
    cached_answers = {}
    if os.path.exists(ANSWERS_CACHE_FILE):
        try:
            with open(ANSWERS_CACHE_FILE, 'r') as f:
                cached_answers = json.load(f)
            print(f"Loaded {len(cached_answers)} cached answers")
        except Exception as e:
            print(f"Error loading cached answers: {e}")
    
    print(f"Running agent on {len(questions_data)} questions...")
    for item in questions_data:
        task_id = item.get("task_id")
        question_text = item.get("question")
        
        if not task_id or question_text is None:
            print(f"Skipping item with missing task_id or question: {item}")
            continue
        
        # Check if we already have a cached answer for this task
        if task_id in cached_answers:
            print(f"Using cached answer for task {task_id}")
            full_response = cached_answers[task_id]['full_response']
            submitted_answer = cached_answers[task_id]['submitted_answer']
            processed_count += 1
        else:
            try:
                # Check for associated files with manual retry
                try:
                    api_url = DEFAULT_API_URL
                    files_url = f"{api_url}/files/{task_id}"
                    files_response = requests.get(files_url, timeout=15)
                    if files_response.status_code == 200:
                        print(f"Task {task_id} has associated files")
                        # Handle files if needed
                except Exception as e:
                    print(f"Error checking for files for task {task_id}: {e}")
                
                # Get agent response
                full_response = agent(question_text)
                
                # Extract final answer
                submitted_answer = extract_final_answer(full_response)
                
                # Cache this answer
                cached_answers[task_id] = {
                    'full_response': full_response,
                    'submitted_answer': submitted_answer
                }
                
                # Save to cache after each question to avoid losing progress
                try:
                    with open(ANSWERS_CACHE_FILE, 'w') as f:
                        json.dump(cached_answers, f)
                except Exception as e:
                    print(f"Warning: Failed to save answer cache: {e}")
                
                processed_count += 1
                
            except Exception as e:
                print(f"Error running agent on task {task_id}: {e}")
                full_response = f"AGENT ERROR: {e}"
                submitted_answer = "Unable to determine"
        
        # Log for display
        results_log.append({
            "Task ID": task_id, 
            "Question": question_text, 
            "Submitted Answer": submitted_answer,
            "Full Response": full_response
        })
        
        print(f"Processed task {task_id}, answer: {submitted_answer}")
    
    # Prepare submission data and save for later submission
    space_id = os.getenv("SPACE_ID")
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
    
    submission_data = {
        "username": username.strip(),
        "agent_code": agent_code,
        "answers": [
            {
                "task_id": task_id,
                "submitted_answer": cached_answers[task_id]["submitted_answer"],
                "reasoning_trace": cached_answers[task_id]["full_response"]
            }
            for task_id in cached_answers
        ]
    }
    
    # Save submission data for later use
    try:
        with open(SUBMISSION_READY_FILE, 'w') as f:
            json.dump(submission_data, f)
        print(f"Saved submission data to {SUBMISSION_READY_FILE}")
    except Exception as e:
        print(f"Warning: Failed to save submission data: {e}")
    
    status_message = f"Processing complete. Processed {processed_count} questions. Ready for submission."
    print(status_message)
    
    results_df = pd.DataFrame(results_log)
    return status_message, results_df

def submit_answers(profile: gr.OAuthProfile | None):
    """
    Submits previously processed answers to the evaluation server.
    """
    if profile:
        username = f"{profile.username}"
        print(f"User logged in: {username}")
    else:
        print("User not logged in.")
        return "Please Login to Hugging Face with the button.", None
    
    # Check if submission data exists
    if not os.path.exists(SUBMISSION_READY_FILE):
        return "No submission data found. Please process questions first.", None
    
    # Load submission data
    try:
        with open(SUBMISSION_READY_FILE, 'r') as f:
            submission_data = json.load(f)
        print(f"Loaded submission data with {len(submission_data['answers'])} answers")
    except Exception as e:
        print(f"Error loading submission data: {e}")
        return f"Error loading submission data: {e}", None
    
    # Update username in case it's different
    submission_data["username"] = username.strip()
    
    # Submit with robust retry mechanism
    api_url = DEFAULT_API_URL
    submit_url = f"{api_url}/submit"
    print(f"Submitting {len(submission_data['answers'])} answers to: {submit_url}")
    
    try:
        # Use manual retry for submission
        max_attempts = 5
        base_wait = 30  # Start with a long wait time
        
        for attempt in range(max_attempts):
            print(f"Submission attempt {attempt+1}/{max_attempts}")
            
            try:
                response = requests.post(submit_url, json=submission_data, timeout=60)
                
                if response.status_code == 200:
                    result_data = response.json()
                    final_status = (
                        f"Submission Successful!\n"
                        f"User: {result_data.get('username')}\n"
                        f"Overall Score: {result_data.get('score', 'N/A')}% "
                        f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
                        f"Message: {result_data.get('message', 'No message received.')}"
                    )
                    print("Submission successful.")
                    
                    # Load and return results for display
                    try:
                        with open(ANSWERS_CACHE_FILE, 'r') as f:
                            cached_answers = json.load(f)
                        
                        # Load questions to display alongside answers
                        with open(QUESTIONS_CACHE_FILE, 'r') as f:
                            questions_data = json.load(f)
                        
                        question_map = {q["task_id"]: q["question"] for q in questions_data}
                        
                        results_log = [
                            {
                                "Task ID": task_id,
                                "Question": question_map.get(task_id, "Unknown"),
                                "Submitted Answer": cached_answers[task_id]["submitted_answer"]
                            }
                            for task_id in cached_answers
                        ]
                        
                        return final_status, pd.DataFrame(results_log)
                    except Exception as e:
                        print(f"Error preparing results display: {e}")
                        return final_status, None
                    
                elif response.status_code == 429:
                    wait_time = base_wait * (2 ** attempt)
                    print(f"Rate limited (429). Waiting {wait_time} seconds before retry...")
                    time.sleep(wait_time)
                else:
                    print(f"Submission failed with status code: {response.status_code}")
                    error_detail = f"Server responded with status {response.status_code}."
                    try:
                        error_json = response.json()
                        error_detail += f" Detail: {error_json.get('detail', response.text)}"
                    except:
                        error_detail += f" Response: {response.text[:500]}"
                    
                    # For non-429 errors, don't retry
                    status_message = f"Submission Failed: {error_detail}"
                    print(status_message)
                    return status_message, None
                    
            except requests.exceptions.RequestException as e:
                print(f"Request error during submission: {e}")
                time.sleep(base_wait)
        
        # If we get here, all attempts failed
        status_message = f"Submission Failed: Maximum retry attempts exceeded."
        print(status_message)
        return status_message, None
        
    except Exception as e:
        status_message = f"An unexpected error occurred during submission: {e}"
        print(status_message)
        return status_message, None

# --- Build Gradio Interface using Blocks ---
with gr.Blocks() as demo:
    gr.Markdown("# Smolagent GAIA Evaluation Runner")
    gr.Markdown(
        """
        **Instructions:**
        1. Log in to your Hugging Face account using the button below.
        2. Click 'Process Questions' to run the agent on all questions and save answers.
        3. After processing is complete, click 'Submit Answers' to submit the answers to the evaluation server.
        ---
        **Note:** Processing questions will take time as the agent processes each question. The agent is specifically configured to 
        format answers according to the GAIA benchmark requirements:
        - Numbers: No commas, no units
        - Strings: No articles, no abbreviations
        - Lists: Comma-separated values following the above rules
        
        Separating processing and submission helps avoid losing work due to rate limiting or other errors.
        """
    )

    gr.LoginButton()

    with gr.Row():
        process_button = gr.Button("Process Questions")
        submit_button = gr.Button("Submit Answers")

    status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
    results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)

    process_button.click(
        fn=process_questions,
        outputs=[status_output, results_table]
    )
    
    submit_button.click(
        fn=submit_answers,
        outputs=[status_output, results_table]
    )

if __name__ == "__main__":
    print("\n" + "-"*30 + " App Starting " + "-"*30)
    # Check for SPACE_HOST and SPACE_ID at startup for information
    space_host_startup = os.getenv("SPACE_HOST")
    space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup

    if space_host_startup:
        print(f"✅ SPACE_HOST found: {space_host_startup}")
        print(f"   Runtime URL should be: https://{space_host_startup}.hf.space")
    else:
        print("ℹ️  SPACE_HOST environment variable not found (running locally?).")

    if space_id_startup: # Print repo URLs if SPACE_ID is found
        print(f"✅ SPACE_ID found: {space_id_startup}")
        print(f"   Repo URL: https://huggingface.co/spaces/{space_id_startup}")
        print(f"   Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
    else:
        print("ℹ️  SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")

    print("-"*(60 + len(" App Starting ")) + "\n")

    print("Launching Gradio Interface for Smolagent GAIA Evaluation...")
    demo.launch(debug=True, share=False)