#!/usr/bin/env python3
"""CallJots API Client — Python SDK.
Usage:
  pip install requests websockets
  python calljots-client.py extract "I will send the report by Friday."
  python calljots-client.py transcribe call.wav
  python calljots-client.py poll <job_id>
"""
import os, sys, json, time, requests

class CallJotsClient:
    def __init__(self, api_key=None, base="http://localhost:8915/api/v1"):
        self.api_key = api_key or os.environ.get("CALLJOTS_API_KEY", "your-api-key-here")
        self.base = base
        self.session = requests.Session()
        self.session.headers.update({"Authorization": f"Bearer {self.api_key}"})

    def extract(self, text, threshold=0.3, use_hmm=True):
        """Extract jots from text (Service 2)."""
        r = self.session.post(f"{self.base}/jots/extract", json={
            "text": text, "threshold": threshold, "use_hmm": use_hmm
        })
        return r.json()

    def transcribe(self, filepath, threshold=0.3):
        """Upload audio for transcription (Service 1)."""
        with open(filepath, "rb") as f:
            r = self.session.post(f"{self.base}/jobs/transcribe",
                files={"file": f}, data={"threshold": str(threshold)})
        return r.json()

    def poll(self, job_id, timeout=300, interval=3):
        """Poll job until complete."""
        start = time.time()
        while time.time() - start < timeout:
            r = self.session.get(f"{self.base}/jobs/{job_id}?include_transcript=true")
            data = r.json().get("data", {})
            if data.get("status") in ("completed", "failed"):
                return data
            time.sleep(interval)
        return {"status": "timeout"}

    def search(self, query="", jot_type="", limit=20):
        """Search jots (Service 5)."""
        params = {"limit": limit}
        if query: params["q"] = query
        if jot_type: params["jot_type"] = jot_type
        r = self.session.get(f"{self.base}/jots/search", params=params)
        return r.json()

    def list_models(self):
        """List available models (Service 13)."""
        r = self.session.get(f"{self.base}/models")
        return r.json()

    def get_usage(self):
        """Get billing usage (Service 14)."""
        r = self.session.get(f"{self.base}/billing/usage")
        return r.json()

    def register_webhook(self, url, events=None):
        """Register a webhook (Service 12)."""
        if events is None:
            events = ["job.completed"]
        r = self.session.post(f"{self.base}/webhooks", json={
            "url": url, "events": events
        })
        return r.json()

    def get_jot(self, jot_id, deep=False):
        """Get jot detail (Service 6)."""
        params = {"deep": "true"} if deep else {}
        r = self.session.get(f"{self.base}/jots/{jot_id}", params=params)
        return r.json()

    def submit_feedback(self, jot_id, correct, corrected_type="", notes=""):
        """Submit feedback on prediction (Service 16)."""
        r = self.session.post(f"{self.base}/feedback", json={
            "jot_id": jot_id, "correct": correct,
            "corrected_type": corrected_type, "notes": notes
        })
        return r.json()

    def health(self):
        """Health check."""
        try:
            r = self.session.get(f"{self.base}/../health/", timeout=5)
            return r.status_code == 200
        except:
            return False


def main():
    if len(sys.argv) < 2:
        print("Usage: calljots-client.py <extract|transcribe|poll|search|models|usage|webhook|health> [args]")
        sys.exit(1)

    client = CallJotsClient()
    cmd = sys.argv[1]

    if cmd == "extract":
        text = " ".join(sys.argv[2:]) or "I will send you the report by Friday. Please review it."
        result = client.extract(text)
        print(json.dumps(result, indent=2))

    elif cmd == "transcribe":
        if len(sys.argv) < 3:
            print("Usage: calljots-client.py transcribe <file.wav>")
            sys.exit(1)
        result = client.transcribe(sys.argv[2])
        print(json.dumps(result, indent=2))

    elif cmd == "poll":
        if len(sys.argv) < 3:
            print("Usage: calljots-client.py poll <job_id>")
            sys.exit(1)
        result = client.poll(sys.argv[2])
        print(json.dumps(result, indent=2))

    elif cmd == "search":
        query = " ".join(sys.argv[2:]) if len(sys.argv) > 2 else ""
        result = client.search(query=query)
        print(json.dumps(result, indent=2))

    elif cmd == "models":
        result = client.list_models()
        print(json.dumps(result, indent=2))

    elif cmd == "usage":
        result = client.get_usage()
        print(json.dumps(result, indent=2))

    elif cmd == "webhook":
        if len(sys.argv) < 3:
            print("Usage: calljots-client.py webhook <url>")
            sys.exit(1)
        result = client.register_webhook(sys.argv[2])
        print(json.dumps(result, indent=2))

    elif cmd == "health":
        ok = client.health()
        print(f"API health: {'OK' if ok else 'FAILED'}")
        sys.exit(0 if ok else 1)

    else:
        print(f"Unknown command: {cmd}")
        sys.exit(1)

if __name__ == "__main__":
    main()