# Install dependencies:
# pip install ollama
# Install Ollama locally and run: ollama pull llama3.2
#
# Demonstrates agency and autonomy with a mock travel provider.
# The provider is simulated; no real flight is searched or booked.

from typing import Any, Dict, List


class TravelProvider:
    """A mock API-like provider returning sample flight options."""

    def flight_lookup(self, departure: str, destination: str) -> Dict[str, Any]:
        return {
            "status_code": 200,
            "flight_options": [
                {"airline": "Alaska Airlines", "departure": departure,
                 "destination": destination, "price": 250},
                {"airline": "Delta", "departure": departure,
                 "destination": destination, "price": 300},
                {"airline": "United", "departure": departure,
                 "destination": destination, "price": 280},
            ],
        }


travel_provider = TravelProvider()


class TravelAgent:
    def __init__(self, name: str):
        self.name = name
        self.goals: List[str] = []
        self.knowledge_base: Dict[str, Any] = {}

    def set_goal(self, goal: str):
        """Agency: define an objective on behalf of the user."""
        self.goals.append(goal)
        print("Goal set:", goal)

    def update_knowledge(self, departure: str, destination: str):
        """Acquire information from the provider and score options."""
        response = travel_provider.flight_lookup(departure, destination)
        if response["status_code"] == 200:
            options = response["flight_options"]
            scored = [{**flight, "score": 1000 / flight["price"]}
                      for flight in options]
            self.knowledge_base["flight_options"] = scored
            print(f"Knowledge updated with {len(scored)} flight options.")
        else:
            print("Failed to fetch flight information.")

    def make_decision(self) -> Dict[str, Any]:
        """Autonomy: independently choose from available information."""
        if "flight_options" not in self.knowledge_base:
            raise ValueError("No flight options available.")
        selected = max(self.knowledge_base["flight_options"],
                       key=lambda item: item["score"])
        print("Decision made: selected", selected["airline"])
        return selected

    def book_travel(self, departure: str, destination: str):
        """Agency: take an action toward the stated objective."""
        print(f"Agent {self.name} is arranging a sample trip.")
        self.set_goal(f"Find flight from {departure} to {destination}")
        self.update_knowledge(departure, destination)
        try:
            flight = self.make_decision()
            # This is only a simulated confirmation, not an actual booking.
            confirmation = f"DEMO-{flight['airline'].upper().replace(' ', '-')}-{self.name.upper()}"
            self.knowledge_base["booking_confirmation"] = confirmation
            print("Sample selection:", flight)
            print("Demo confirmation:", confirmation)
        except (ValueError, KeyError) as error:
            print("Selection failed:", error)


if __name__ == "__main__":
    agent = TravelAgent("Vivek")
    agent.book_travel("Hyderabad", "Delhi")
