#!/usr/bin/env python3
"""
Limos API Reference - chat.ia.limos.fr
=======================================
API OpenAI-compatible (pas de /v1/). Accepte un JWT en Bearer.

Usage:
    python3 limos.py "ta question"
    echo "ta question" | python3 limos.py

Connexion depuis Hermes:
    hermes chat -m limos -q "ta question"
    (alias configuré dans ~/.hermes/config.yaml)

Pour récupérer un nouveau JWT:
    Navigateur > F12 > Application > Local Storage > clé "token"
"""

import json, urllib.request, sys
from pathlib import Path

# ── Config ──
TOKEN_FILE = Path.home() / ".limos_token"
URL = "https://chat.ia.limos.fr/openai/chat/completions"
MODEL = "general"

# ── Token ──
if not TOKEN_FILE.exists():
    print(f"❌ Token file not found: {TOKEN_FILE}", file=sys.stderr)
    sys.exit(1)

token = TOKEN_FILE.read_text().strip()
if not token:
    print("❌ Token file is empty", file=sys.stderr)
    sys.exit(1)

# Vérifier expiration
try:
    import base64, datetime
    payload_b64 = token.split(".")[1]
    padding = 4 - len(payload_b64) % 4
    if padding != 4:
        payload_b64 += "=" * padding
    payload = json.loads(base64.urlsafe_b64decode(payload_b64))
    exp = datetime.datetime.fromtimestamp(payload["exp"])
    remaining = exp - datetime.datetime.now()
    if remaining.total_seconds() < 0:
        print(f"❌ Token expiré le {exp}", file=sys.stderr)
        sys.exit(1)
    print(f"ℹ️  Token valide jusqu'au {exp.date()} ({remaining.days}j restants)", file=sys.stderr)
except Exception:
    pass  # silencieux si le décodage échoue

# ── Message ──
msg = sys.argv[1] if len(sys.argv) > 1 else sys.stdin.read().strip()
if not msg:
    print("Usage: python3 limos.py 'ta question'", file=sys.stderr)
    sys.exit(1)

# ── Requête ──
payload = json.dumps({
    "model": MODEL,
    "messages": [{"role": "user", "content": msg}],
    "stream": False
}).encode()

req = urllib.request.Request(URL, data=payload, headers={
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
})

try:
    with urllib.request.urlopen(req, timeout=30) as resp:
        data = json.loads(resp.read())
        print(data["choices"][0]["message"]["content"])
except urllib.error.HTTPError as e:
    body = e.read().decode()
    print(f"❌ HTTP {e.code}: {body[:300]}", file=sys.stderr)
    sys.exit(1)
