from crewai import Agent, Task, Crew, Process
from textwrap import dedent
from datetime import date

from config.TripPlanner import browser_tools, calculator_tools, search_tools
import os

#Model options
llm_models = [
    "gemini/gemini-1.5-flash",
    "gemini/gemini-1.5-pro",
    "gemini/gemini-pro"
]

selected_model = llm_models[0]
def configure_api_keys(gemini_api_key):
    if not gemini_api_key:
        raise ValueError("Gemini API key is required")
    os.environ['GEMINI_API_KEY'] = gemini_api_key

def set_model(selected_model_name):
    global selected_model
    selected_model = selected_model_name

def run_crew_tp(gemini_api_key, origin, cities, trip_date, interests):
    try:
        # Configure API keys (no search tool used)
        configure_api_keys(gemini_api_key)

        # Agents
        city_selection_agent = Agent(
            role='City Selection Expert',
            goal='Select the best city based on weather, season, and prices',
            backstory='An expert in analyzing travel  data to pic idea; destinations',
            tools=[
                search_tools.SearchTools.search_internet, browser_tools.
                BrowserTools.scrape_and_summarize_website
            ],
            llm=selected_model,
            verbose=True)

        local_expert = Agent(
            role='Local Expert at this city',
            goal='Provide the BEST insights about the selected city',
            backstory="""A knowledgeable local guide with extensive information
                about the city, it's attractions and customs""",
            tools=[
                search_tools.SearchTools.search_internet,
                browser_tools.BrowserTools.scrape_and_summarize_website,
            ],
            llm=selected_model,
            verbose=True)

        travel_concierge = Agent(
        role='Amazing Travel Concierge',
        goal="""Create the most amazing travel itineraries with budget and 
        packing suggestions for the city""",
        backstory="""Specialist in travel planning and logistics with 
        decades of experience""",
        tools=[
            search_tools.SearchTools.search_internet,
            browser_tools.BrowserTools.scrape_and_summarize_website,
            calculator_tools.CalculatorTools.calculate,
        ],
        llm=selected_model,
        verbose=True)

        #Tasks
        identity_task = Task(
            description=dedent(f"""
                Analyze and select the best city for the trip based 
                on specific criteria such as weather patterns, seasonal
                events, and travel costs. This task involves comparing
                multiple cities, considering factors like current weather
                conditions, upcoming cultural or seasonal events, and
                overall travel expenses. 
                
                Your final answer must be a detailed
                report on the chosen city, and everything you found out
                about it, including the actual flight costs, weather 
                forecast and attractions.

                Traveling from: {origin}
                City Options: {cities}
                Trip Date: {trip_date}
                Traveler Interests: {interests}
            """),
            agent=city_selection_agent,
            expected_output="Detailed report on the chosen city including flight costs, weather forecast, and attractions"
        )

        gather_task = Task(
            description=dedent(f"""
                As a local expert on this city you must compile an 
                in-depth guide for someone traveling there and wanting 
                to have THE BEST trip ever!
                Gather information about key attractions, local customs,
                special events, and daily activity recommendations.
                Find the best spots to go to, the kind of place only a
                local would know.
                This guide should provide a thorough overview of what 
                the city has to offer, including hidden gems, cultural
                hotspots, must-visit landmarks, weather forecasts, and
                high level costs.
                
                The final answer must be a comprehensive city guide, 
                rich in cultural insights and practical tips, 
                tailored to enhance the travel experience.

                Trip Date: {trip_date}
                Traveling from: {origin}
                Traveler Interests: {interests}
            """),
            agent=local_expert,
            expected_output="Comprehensive city guide including hidden gems, cultural hotspots, and practical travel tips"
        )

        plan_task = Task(
            description=dedent(f"""
                Expand this guide into a full 7-day travel 
                itinerary with detailed per-day plans, including 
                weather forecasts, places to eat, packing suggestions, 
                and a budget breakdown.
                
                You MUST suggest actual places to visit, actual hotels 
                to stay and actual restaurants to go to.
                
                This itinerary should cover all aspects of the trip, 
                from arrival to departure, integrating the city guide
                information with practical travel logistics.
                
                Your final answer MUST be a complete expanded travel plan,
                formatted as markdown, encompassing a daily schedule,
                anticipated weather conditions, recommended clothing and
                items to pack, and a detailed budget, ensuring THE BEST
                TRIP EVER. Be specific and give it a reason why you picked
                each place, what makes them special! 
                
                Trip Date: {trip_date}
                Traveling from: {origin}
                Traveler Interests: {interests}
            """),
            agent=travel_concierge,
            expected_output="Complete expanded travel plan with daily schedule, weather conditions, packing suggestions, and budget breakdown",
            output_file = 'trip_planner.md'
        )

        crew = Crew(
            agents=[city_selection_agent, local_expert, travel_concierge],
            tasks=[identity_task, gather_task, plan_task],
            process=Process.sequential,
            output_log_file=True,
            verbose=True
        )

        crew.kickoff(inputs={
            'origin': origin,
            'cities': cities,
            'trip_date': trip_date,
            'interests': interests
        })

        with open("trip_planner.md", "r", encoding='utf-8') as f:
            plan = f.read()
        with open("logs.txt", 'r', encoding='utf-8') as f:
            logs = f.read()
        with open("logs.txt", 'w', encoding='utf-8') as f:
            f.truncate(0)
        return plan, logs

    except Exception as e:
        return f"Error: {str(e)}", str(e)