import os, sys
import yaml
import json
from enum import Enum
import gradio as gr
import requests
import inspect
import subprocess
import dateparser
from bs4 import BeautifulSoup
import regex
import pandas as pd
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, BitsAndBytesConfig
from smolagents import CodeAgent, VisitWebpageTool, PromptTemplates, PlanningPromptTemplate, ManagedAgentPromptTemplate, FinalAnswerPromptTemplate
from smolagents.models import ChatMessage
from custom_tools import (
    ReadFileTool, ReadExcelTool, ReadContentFromURLTool, 
    WebpageStructureAnalyzerTool, SummarizeWebpageContentTool, ExtractTableFromWebpageTool, GetWikipediaSectionTool, 
    ImageContentDescriberTool, TranscribeAudioTool, CachedWebSearchTool, CachedWikiTool, PreloadedPythonTool
)
from huggingface_hub import hf_hub_download

subprocess.run(["playwright", "install"], check=True)

# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
GAIA_DATASET_URL_1 = "https://huggingface.co/datasets/gaia-benchmark/GAIA/blob/main/2023/validation"
GAIA_DATASET_URL_2 = "https://huggingface.co/datasets/gaia-benchmark/GAIA/blob/main/2023/test"
MODEL_ID = "Qwen/Qwen3-32B"
# MODEL_ID = "Qwen/Qwen2.5-Coder-32B-Instruct"

# In your app.py (or a helper module like your system_prompts.py)
import yaml
import os

def check_token_access():
    token = os.environ.get("HF_TOKEN", "")
    if not token:
        print("❌ No token found")
        return
    headers = {"Authorization": f"Bearer {token}"}
    url = f"https://huggingface.co/{MODEL_ID}/resolve/main/config.json"
    
    try:
        r = requests.get(url, headers=headers, timeout=10)
        print(f"🔍 Token test response: {r.status_code}")
        if r.status_code == 200:
            print("✅ Token access confirmed for gated model.")
        elif r.status_code == 403:
            print("❌ 403 Forbidden: Token does not have access.")
        else:
            print("⚠️ Unexpected status:", r.status_code)
    except Exception as e:
        print("❌ Token check failed:", e)

# --- Basic Model Definition ---
# ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
class BasicModel:
    def __init__(self, model_id, hf_token=""):
        print("BasicAgent initialized.")
        print("ENV-HF_TOKEN-LEN", len(hf_token), file=sys.stderr)
        check_token_access()
        
        # Initialize the model
        # model = HfApiModel(model_id=model_id,
        #                   # format="text-generation",
        #                   token=os.environ["HF_TOKEN"], 
        #                   max_tokens=2048,
        #                   temperature=0.0
        #                  )
        
        # Download the model weights to the local machine and build the pipeline
        quantization_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_compute_dtype=torch.float16, 
            bnb_4bit_use_double_quant=True,
        )
        tok = AutoTokenizer.from_pretrained(model_id, token=hf_token)
        mod = AutoModelForCausalLM.from_pretrained(
            model_id,
            torch_dtype=torch.float16,
            device_map="auto",  ## auto-distributes to GPU
            # attn_implementation="flash_attention_2", ## Not able to install 'flash-attn' here for now
            token=hf_token,
            trust_remote_code=True, ## <- Use the custom code that isn't part of the base transformers library yet
            quantization_config=quantization_config ## <- Load 4-bit quantization because vRAM is not big enough
        )
        self.pipe = pipeline(
            "text-generation",
            model=mod,
            tokenizer=tok,
            max_new_tokens=1024,
            do_sample=True,
            return_full_text=False,      # <— only get the completion, not the prompt + completion
            temperature=0.1, 
        )

    def _serialize_messages(self, messages):
        # This serialization might need adjustment based on how CodeAgent sends prompts.
        # It needs to handle both initial strings and potential chat histories (as a list of ChatMessage objects).
        if isinstance(messages, str):
            return f"<|im_start|>user\n\n{messages}<|im_end|><|im_start|>assistant<|im_end|>\n\n"
            
        prompt = []
        for m in messages: ## <- For each ChatMessage object
            # Read the roles
            role = m.role if hasattr(m, 'role') else m.get('role', 'user')
            role = role.value if isinstance(role, Enum) else role
            # Read the content texts
            content = list(m.values())[1]
            content_text = ""
            if isinstance(content, list): ## <- If m.content is a list of dicts, e.g. [{'type':'text', 'text': ...}]
                 content_text = "".join([c.get('text', '') for c in content if c.get('type') == 'text'])
            elif isinstance(content, str): ## <- If m.content is simply a string
                 content_text = content
            prompt.append(f"<|im_start|>{role}\n\n{content_text}<|im_end|>") # Qwen3 format

        # print(f"{role}: {content_text}") ## <- Print the last message in log
        
        # Add the assistant prompt start
        prompt.append("<|im_start|>assistant\n\n")
        
        return "".join(prompt)
        
    def generate(self, prompt: str | list, stop_sequences=None, **kwargs) -> str: ## <- 'prompt' is either a string or a list of ChatMessages
        # 1. Build the HF kwargs
        allowed = {"max_new_tokens", "temperature", "top_k", "top_p"}
        gen_kwargs = {k: v for k, v in kwargs.items() if k in allowed}
        
        # 2. Get the response
        terminators = [
            self.pipe.tokenizer.eos_token_id,
            self.pipe.tokenizer.convert_tokens_to_ids("<|endoftext|>")
        ]
        prompt_str = self._serialize_messages(prompt)
        outputs = self.pipe(prompt_str, eos_token_id=terminators, **gen_kwargs)
        response = outputs[0]["generated_text"]
        assert isinstance(response, str)

        # 3. The response consists of a <think></think> block and a JSON block. we want to separate the two blocks.
        ## Save the <think></think> block to print in the log
        try:
            # This regex finds the content between <think> and </think>
            thought_pattern = r"<think>(.*?)</think>"
            # re.DOTALL allows the '.' to match newline characters
            match = regex.search(thought_pattern, response, flags=regex.DOTALL)
            if match:
                # .group(1) gets the content captured by the (.*?) part of the pattern
                full_think_block = match.group(0)
                thought_content = match.group(1).strip()
                print(f"--- CAPTURED THOUGHT ---\n{thought_content}\n------------------------")
                # Remove the entire think block from the response
                response = response.replace(full_think_block, "").strip()
        except Exception as e:
            # This is just for logging, so we don't want it to crash the main process.
            print(f"Could not extract <think> block: {e}")
            
        ## Pass the JSON block as the 'response'
        try:
            # Find the first '{' and the last '}'
            start_index = response.find('{')
            end_index = response.rfind('}')
            # If both braces are found, extract the substring
            if start_index != -1 and end_index != -1 and end_index > start_index:
                json_substring = response[start_index : end_index + 1]
                # Try to parse the substring to ensure it's valid JSON
                json.loads(json_substring)
                # If it's valid, we replace the original response with just the clean JSON part.
                response = json_substring  

                print("\n -------------JSON string is successfully extracted!-------\n----------------\n")
                
        # If no valid JSON is found, we proceed with the original response string.
        except (json.JSONDecodeError, TypeError):
            # Pass silently and let the framework handle the potentially malformed string.
            pass

        # 4. Optionally map SmolAgents’ stop_sequences → HF pipeline’s 'stop'
        if stop_sequences:
            # find the earliest occurrence of any stop token
            cuts = [response.find(s) for s in stop_sequences if response.find(s) != -1]
            if cuts:
                response = response[: min(cuts)]

        # 5. NEW: Parse, Fix, and Re-serialize the agent's code output
        try:
            # The agent's response is expected to be a JSON string, according to the system prompt
            # Parse it into a Python dictionary
            agent_output_dict = json.loads(response)
    
            # If the 'code' key exists in the dictionary, parse it
            if "code" in agent_output_dict and isinstance(agent_output_dict["code"], str):
                
                # This is the core fix from the evaluation report's advice.
                # We take the raw code string and wrap it in the required markdown format.
                raw_code = agent_output_dict["code"].strip()
                
                # We also clean up potential markdown fences the LLM might have added itself
                # raw_code = regex.sub(r"^(?:```(?:py|python)?\n)?(.*?)(?:\n```)?$", r"\1", raw_code, flags=regex.DOTALL)
                cleaned_code = regex.sub(r"^\s*```(?:py|python)?\n(.*?)\n```\s*$", r"\1", raw_code, flags=regex.DOTALL)
    
                # formatted_code = f"```py\n{raw_code}\n```"
                
                # We update the dictionary with the correctly formatted code.
                agent_output_dict["code"] = cleaned_code
    
                # We convert the corrected Python dictionary back into a JSON string
                # to pass back to the smol-agent framework.
                response = json.dumps(agent_output_dict)
    
        except json.JSONDecodeError:
            # If the LLM produces a response that is not valid JSON, we don't crash.
            # We simply pass it along as is and let the agent framework handle it.
            # This often happens when the agent is just having a "conversation" or returning a final answer without code.
            pass
        
        # 6. Wrap back into a chat message dict
        return ChatMessage(role="assistant", content=response)
        # return {
        #     "role": 'assistant',
        #     "content": [{"type": "text", "text": response}],
        # }

    __call__ = generate

def run_and_submit_all( profile: gr.OAuthProfile | None):
    """
    Fetches all questions, runs the BasicAgent on them, submits all answers,
    and displays the results.
    """
    # --- Determine HF Space Runtime URL and Repo URL ---
    space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
    hf_token = os.getenv("HF_TOKEN")

    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

    api_url = DEFAULT_API_URL
    questions_url = f"{api_url}/questions"
    submit_url = f"{api_url}/submit"

    # 1. Instantiate Agent ( modify this part to create your agent)
    try:
        # (1) Create the LLM wrapper
        llm_model = BasicModel(model_id=MODEL_ID, hf_token=hf_token)
        # (2) Create the tools
        tools_for_agent = [
            ReadFileTool(), 
            ReadExcelTool(),
            ReadContentFromURLTool(),
            WebpageStructureAnalyzerTool(),
            SummarizeWebpageContentTool(),
            ExtractTableFromWebpageTool(),
            GetWikipediaSectionTool(),
            ImageContentDescriberTool(),
            TranscribeAudioTool(),
            CachedWikiTool(),
            CachedWebSearchTool(),
            PreloadedPythonTool(),
            VisitWebpageTool()
        ]
        # (3) Create the system prompt
        # Assuming 'my_default_system_prompt.yaml' is in the same directory as app.py
        current_dir = os.path.dirname(os.path.abspath(__file__))
        prompt_yaml_file_path = os.path.join(current_dir, "default_system_prompt.yaml")
        with open(prompt_yaml_file_path, 'r', encoding='utf-8') as f:
            data = yaml.safe_load(f)
        # (4) Create the prompt templates to plug in CodeAgent
        my_prompt_templates = PromptTemplates(system_prompt=data['system_prompt'],
                                            planning=PlanningPromptTemplate(initial_plan=data['planning']['initial_plan'], 
                                                                            update_plan_pre_messages=data['planning']['update_plan_pre_messages'], 
                                                                            update_plan_post_messages=data['planning']['update_plan_post_messages']),
                                            managed_agent=ManagedAgentPromptTemplate(task=data['managed_agent']['task'], 
                                                                                     report=data['managed_agent']['report']),
                                            final_answer=FinalAnswerPromptTemplate(pre_messages=data['final_answer']['pre_messages'], 
                                                                                   post_messages=data['final_answer']['post_messages']))
        # (5) Create the CodeAgent, passing the LLM wrapper and tools
        agent = CodeAgent(model=llm_model, 
                          tools=tools_for_agent,
                          prompt_templates=my_prompt_templates,
                          max_steps=8,
                          add_base_tools=True,
                          additional_authorized_imports=["pandas", "dateparser", "bs4", "regex"])
    except Exception as e:
        print(f"Error instantiating agent: {e}")
        return f"Error initializing agent: {e}", None
    # In the case of an app running as a Hugging Face space, this link points toward your codebase ( useful for others, so please keep it public)
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
    print(agent_code)

    # 2. Fetch Questions
    print(f"Fetching questions from: {questions_url}")
    try:
        response = requests.get(questions_url, timeout=15)
        response.raise_for_status()
        questions_data = response.json()
        if not questions_data:
             print("Fetched questions list is empty.")
             return "Fetched questions list is empty or invalid format.", None
        print(f"Fetched {len(questions_data)} questions.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching questions: {e}")
        return f"Error fetching questions: {e}", None
    except requests.exceptions.JSONDecodeError as e:
         print(f"Error decoding JSON response from questions endpoint: {e}")
         print(f"Response text: {response.text[:500]}")
         return f"Error decoding server response for questions: {e}", None
    except Exception as e:
        print(f"An unexpected error occurred fetching questions: {e}")
        return f"An unexpected error occurred fetching questions: {e}", None

    # Find those with attachments
    # questions_data = [questions_data[i] for i in [3,9,11,13,19]]
    
    # 3. Run your Agent
    results_log = []
    answers_payload = []
    print(f"Running agent on {len(questions_data)} questions...")
    for item in questions_data:
        print(item)
        task_id = item.get("task_id")
        question_text = item.get("question")

        # Check for an associated filename and enhance the prompt
        file_name = item.get("file_name")

        if file_name:
            print(f"Task {task_id} requires file: '{file_name}'. Downloading via hf_hub_download...")

            file_downloaded = False
            local_file_path = None # Will be updated if download is successful
            repo_id = "gaia-benchmark/GAIA"
            potential_paths = [
                    f"2023/validation/{file_name}",
                    f"2023/test/{file_name}"
                ]
            
            for path_in_repo in potential_paths:
                try:
                    print(f"Attempting to download from repo path: '{path_in_repo}'")
                    # Use the official library to download the file
                    local_file_path = hf_hub_download(
                        repo_id=repo_id,
                        filename=path_in_repo,
                        repo_type="dataset",
                        token=hf_token
                    )
                    
                    print(f"Successfully downloaded '{file_name}' to cache path: {local_file_path}")
                    # Inform the agent about the successful download and the exact path
                    question_text += f"\n\n[System Note: The required file named '{file_name}' has been successfully downloaded and is available for analysis at the path '{local_file_path}'.]"
                    file_downloaded = True
                    break # Exit the loop on success

                except HfHubHTTPError as e:
                    # Specifically catch 404 Not Found errors and try the next path
                    if e.response.status_code == 404:
                        print(f"File not found at '{path_in_repo}'. Trying next location.")
                        continue
                    else:
                        # For other HTTP errors (like 401), stop trying
                        print(f"HTTP Error {e.response.status_code} downloading '{path_in_repo}'. Aborting download for this file. Error: {e}")
                        break
                except Exception as e:
                    # For other exceptions (like network issues), stop trying
                    print(f"An unexpected error occurred downloading '{path_in_repo}': {e}")
                    break
            
            if not file_downloaded:
                print(f"Failed to download '{file_name}' from all provided sources.")
                question_text += f"\n\n[System Note: A file named '{file_name}' was required for this task, but it could not be downloaded. Please report that the file is inaccessible.]"
            
        if not task_id or question_text is None:
            print(f"Skipping item with missing task_id or question: {item}")
            continue
        try:
            submitted_answer = agent.run(question_text)
            answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
            results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
        except Exception as e:
            error_message = str(e)
            # Check if the error is the one we want to handle specially
            if "max steps" in error_message.lower():
                print(f"Max steps reached for task {task_id}. Forcing a final answer.")
                
                # Try to get the agent's last thought for a more informative answer.
                # Note: This depends on the 'smolagents' library exposing the history.
                # The attribute might be 'agent.history', 'agent.messages', etc.
                last_thought = ""
                if hasattr(agent, 'history') and agent.history:
                    # Get the content of the last message from the agent
                    last_thought = agent.history[-1].content
    
                forced_answer = f"Error: Max steps reached. The agent's last thought was: '{last_thought}'"
                
                # Submit the forced answer
                answers_payload.append({"task_id": task_id, "submitted_answer": forced_answer})
                results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": forced_answer})
            else:
                # Handle all other errors (like CUDA out of memory) as before
                print(f"Error running agent on task {task_id}: {e}")
                results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})

    if not answers_payload:
        print("Agent did not produce any answers to submit.")
        return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)

    # 4. Prepare Submission 
    submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
    status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
    print(status_update)

    # 5. Submit
    print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
    try:
        response = requests.post(submit_url, json=submission_data, timeout=60)
        response.raise_for_status()
        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.")
        results_df = pd.DataFrame(results_log)
        return final_status, results_df
    except requests.exceptions.HTTPError as e:
        error_detail = f"Server responded with status {e.response.status_code}."
        try:
            error_json = e.response.json()
            error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
        except requests.exceptions.JSONDecodeError:
            error_detail += f" Response: {e.response.text[:500]}"
        status_message = f"Submission Failed: {error_detail}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except requests.exceptions.Timeout:
        status_message = "Submission Failed: The request timed out."
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except requests.exceptions.RequestException as e:
        status_message = f"Submission Failed: Network error - {e}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df
    except Exception as e:
        status_message = f"An unexpected error occurred during submission: {e}"
        print(status_message)
        results_df = pd.DataFrame(results_log)
        return status_message, results_df


# --- Build Gradio Interface using Blocks ---
with gr.Blocks() as demo:
    gr.Markdown("# Basic Agent Evaluation Runner")
    gr.Markdown(
        """
        **Instructions:**
        1.  Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
        2.  Log in to your Hugging Face account using the button below. This uses your HF username for submission.
        3.  Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
        ---
        **Disclaimers:**
        Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
        This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance, for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
        """
    )

    gr.LoginButton()

    run_button = gr.Button("Run Evaluation & Submit All Answers")

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

    run_button.click(
        fn=run_and_submit_all,
        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 Basic Agent Evaluation...")
    demo.launch(debug=True, share=False)