"""
Lab 1.7: Your First Agent

Build a single-tool agent from scratch.

Objective: Create an agent that reads a file and answers questions about its contents.
Works offline with mock LLM if no API key is set.
"""

import os
import sys

# Import mock LLM client for offline execution
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '_shared'))
try:
    from mock_llm import MockAnthropic as Anthropic
    client = Anthropic()
except ImportError:
    from anthropic import Anthropic
    client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

# TODO 1: Define your tool schema
# This tool reads a file and returns its contents
FILE_READ_TOOL = {
    "name": "read_file",
    "description": "Read the contents of a file at the given path",
    "input_schema": {
        "type": "object",
        "properties": {
            "path": {
                "type": "string",
                "description": "The path to the file to read"
            },
            "reasoning": {
                "type": "string",
                "description": "Why are you reading this file?"
            }
        },
        "required": ["path", "reasoning"]
    }
}

TOOLS = [FILE_READ_TOOL]


# TODO 2: Implement the tool
def execute_tool(tool_name: str, tool_args: dict) -> str:
    """Execute a tool and return its result."""
    if tool_name == "read_file":
        path = tool_args["path"]
        # Your code here: read the file and return its contents
        # Handle FileNotFoundError gracefully
        pass  # TODO


# TODO 3: Implement the agent loop
def run_agent(prompt: str, file_path: str) -> str:
    """
    Run the agent with a user prompt.
    
    The agent should:
    1. Call the LLM with the prompt and available tools
    2. If the LLM calls a tool, execute it and feed the result back
    3. If the LLM produces a final answer, return it
    4. Stop after MAX_ITERATIONS to prevent infinite loops
    
    HINT: You'll need an LLM client. Use any provider you have access to.
    HINT: The loop pattern is: call LLM → check response → if tool: execute → feed back → repeat
    HINT: Check if response has tool_calls or content to decide whether to continue
    """
    # You'll need an LLM client - import one from anthropic, openai, etc.
    pass  # TODO


# TODO 4: Main entry point
if __name__ == "__main__":
    import sys
    
    if len(sys.argv) < 3:
        print("Usage: python starter.py <file_path> <question>")
        print("Example: python starter.py data.txt 'What is this file about?'")
        sys.exit(1)
    
    file_path = sys.argv[1]
    question = sys.argv[2]
    
    result = run_agent(question, file_path)
    print(f"\nFinal answer:\n{result}")
