#!/usr/bin/env python3
"""
Klient agent0 oparty na OpenHands SDK.

Łączy się z MCP gateway i uruchamia interaktywną sesję agenta.
"""

import json
import os
import sys

from pydantic import SecretStr

from openhands.sdk import LLM, Agent, Conversation, LLMSummarizingCondenser
from openhands.sdk.workspace import LocalWorkspace

from visualizer import DarkTerminalVisualizer

CONFIG_PATH = os.path.join(os.path.dirname(__file__), "..", "..", "conf", "agent0.json")


def load_config() -> dict:
    with open(CONFIG_PATH) as f:
        return json.load(f)


def main():
    config = load_config()
    sekcja = (config.get("providers") or {}).get("anthropic")
    if not isinstance(sekcja, dict):
        print("Błąd: brak sekcji providers.anthropic w conf/agent0.json")
        sys.exit(1)
    api_key = sekcja.get("api_key", "")
    if not api_key or api_key.startswith("sk-..."):
        print("Błąd: ustaw providers.anthropic.api_key w conf/agent0.json")
        sys.exit(1)

    gateway_url = config.get("gateway_url", "http://127.0.0.1:8000/mcp/")
    model = sekcja.get("model", "claude-opus-4-7")

    print(f"Model: {model} | Gateway: {gateway_url}")
    print("Wpisz wiadomość (Ctrl+C = wyjście)\n")

    llm = LLM(model=model, api_key=SecretStr(api_key))
    agent = Agent(
        llm=llm,
        # mcp_config={"mcpServers": {"gateway": {"url": gateway_url}}},
        include_default_tools=[],
        condenser=LLMSummarizingCondenser(llm=llm),
        system_prompt_filename=os.path.join(os.path.dirname(__file__), "system_prompt.j2"),
    )

    workspace = LocalWorkspace(working_dir=os.getcwd())
    conv = Conversation(agent=agent, workspace=workspace, visualizer=DarkTerminalVisualizer())

    while True:
        try:
            user_input = input("Ty: ").strip()
        except (EOFError, KeyboardInterrupt):
            print("\nDo widzenia!")
            break

        if not user_input:
            continue

        conv.send_message(user_input)
        conv.run()


if __name__ == "__main__":
    main()
