import sys
import dspy
from experts.dnd_agent import DnDRAG

def main():
    # 1. Setup the LLM
    print("🚀 Initializing Qwen-8B via LM Studio...")
    lm = dspy.LM("lm_studio/qwen/qwen3-8b", api_base="http://192.168.0.49:1234/v1/")
    dspy.configure(lm=lm)

    # 2. Load the RAG System (only happens once!)
    print("📚 Loading FAISS index and campaign notes...")
    try:
        rag_system = DnDRAG()
        print("✅ Ready! Ask me anything about the campaign. (Type 'exit' or 'q' to quit)")
    except Exception as e:
        print(f"❌ Failed to initialize: {e}")
        return

    # 3. Interactive Loop
    while True:
        try:
            print("\n" + "─" * 30)
            query = input("📝 Query: ").strip()

            # Exit conditions
            if query.lower() in ["exit", "quit", "q"]:
                print("Farewell, traveler. Good luck on your quest!")
                break
            
            if not query:
                continue

            print("🔍 Searching and thinking...")
            response = rag_system(question=query)

            # Print Response
            print("\n📜 AI RESPONSE:")
            print(response.answer)

        except KeyboardInterrupt:
            print("\n\nExiting... See you next session!")
            sys.exit(0)
        except Exception as e:
            print(f"\n⚠️ An error occurred: {e}")

if __name__ == "__main__":
    main()