# Plow Chat API quickstart: one-time setup, then send and listen.
# pip install httpx websockets
# PLOW_API_BASE overrides the API root (default https://api.plow.co).
import json
import os
import time

import httpx
from websockets.sync.client import connect

API = os.environ.get("PLOW_API_BASE", "https://api.plow.co")
WS = API.replace("http", "ws", 1)

# One-time setup: sign in by text
setup = httpx.Client(base_url=API)
a = setup.post("/v1/auth/activate", json={}).json()
print(f'Text "Plow Activate: {a["display_code"]}" to {a["send_to"]}')

secret = {"activation_secret": a["activation_secret"]}
while True:
    r = setup.post("/v1/auth/activate/redeem", json=secret).json()
    if r["status"] == "verified":
        break
    time.sleep(2)
setup.headers["Authorization"] = f"Bearer {r['token']}"

# One-time setup: create your agent
lines = setup.get("/v1/lines").json()["data"]
line = next(ln for ln in lines if ln["provider_type"] == "imessage" and ln["available"])
agent = setup.post(
    "/v1/agents",
    json={"line_uid": line["uid"], "provider": "self_hosted", "name": "my-agent"},
).json()
AGENT_TOKEN = agent["token"]  # works on this line only
print("Now text your agent at", line["provider_key"])

# The client
plow = httpx.Client(
    base_url=API,
    headers={"Authorization": f"Bearer {AGENT_TOKEN}"},
)


# 1. Send
def send(chat_uid, text):
    plow.post(f"/v1/chats/{chat_uid}/typing", json={"action": "start"})
    plow.post(f"/v1/chats/{chat_uid}/messages", json={"body": text})


# 2. Listen and reply
ticket = plow.post("/v1/ws/ticket", json={}).json()["ticket"]
with connect(f"{WS}/v1/ws?ticket={ticket}") as ws:
    for frame in ws:
        event = json.loads(frame)
        if event.get("event_type") != "message_received":
            continue
        msg = event["data"]["message"]
        if msg["direction"] == "inbound":
            send(msg["chat_uid"], f"**Got it:** {msg['body']}")
