"""Учебная CRM на SQLite. Приёмник слушает только 127.0.0.1:8765."""
import argparse
import http.client
import json
import os
import sqlite3
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import quote


API_HOST = "api.voicee.ru"
BASE = "/v1/replicate/v1"
SAMPLE = "https://voicee.ru/assets/audio/text-voice-lesson.m4a"


def api(method, path, body=None, request_key=None):
    headers = {"Authorization": "Bearer " + os.environ["VOICEE_API_KEY"]}
    if request_key is not None:
        headers["Idempotency-Key"] = request_key
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode()
    conn = http.client.HTTPSConnection(API_HOST, timeout=15)
    try:
        conn.request(method, BASE + path, data, headers)
        response = conn.getresponse()
        if not 200 <= response.status < 300:
            raise RuntimeError(f"Voicee HTTP {response.status}")
        return json.load(response)
    finally:
        conn.close()


def open_crm(filename):
    db = sqlite3.connect(filename)
    db.executescript("""
        CREATE TABLE IF NOT EXISTS jobs (
            id TEXT PRIMARY KEY, card TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS notes (
            prediction_id TEXT PRIMARY KEY REFERENCES jobs(id), body TEXT NOT NULL
        );
    """)
    return db


def read_prediction(job_id):
    return api("GET", "/predictions/" + quote(job_id, safe=""))


def receive(db, notice, fetch=read_prediction):
    if not isinstance(notice, dict) or not isinstance(notice.get("id"), str):
        return 400
    job_id = notice["id"]
    if not db.execute("SELECT 1 FROM jobs WHERE id = ?", (job_id,)).fetchone():
        return 404
    if db.execute("SELECT 1 FROM notes WHERE prediction_id = ?", (job_id,)).fetchone():
        return 204
    job = fetch(job_id)
    if not isinstance(job, dict) or job.get("id") != job_id:
        return 503
    if job.get("status") in ("failed", "canceled", "aborted"):
        return 204
    if job.get("status") != "succeeded" or not isinstance(job.get("output"), str):
        return 503
    with db:
        db.execute("""INSERT INTO notes (prediction_id, body) VALUES (?, ?)
                      ON CONFLICT(prediction_id) DO NOTHING""", (job_id, job["output"]))
    return 204


class Callback(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != "/voicee":
            self.send_error(404)
            return
        try:
            length = int(self.headers.get("Content-Length", "0"))
            if not 0 < length <= 16 * 1024 * 1024:
                self.send_error(413)
                return
            notice = json.loads(self.rfile.read(length))
        except (ValueError, RecursionError):
            self.send_error(400)
            return
        try:
            code = receive(self.server.db, notice)
        except (OSError, ValueError, http.client.HTTPException, RuntimeError, sqlite3.Error):
            code = 503
        self.send_response(code)
        self.end_headers()


def demo():
    db = open_crm(":memory:")
    with db:
        db.execute("INSERT INTO jobs VALUES (?, ?)", ("demo-1", "demo-card"))
    notice = {"id": "demo-1"}
    fixture = {"id": "demo-1", "status": "succeeded", "output": "Занятие начнётся в десять тридцать."}
    for delivery in (1, 2):
        code = receive(db, notice, lambda job_id: fixture)
        print(f"Доставка {delivery}: HTTP {code}")
    card, text = db.execute(
        "SELECT card, body FROM jobs JOIN notes ON prediction_id = jobs.id"
    ).fetchone()
    print(f"{card}: {text}")
    print("Заметок:", db.execute("SELECT count(*) FROM notes").fetchone()[0])
    db.close()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    commands.add_parser("demo")
    commands.add_parser("serve")
    submit = commands.add_parser("submit")
    submit.add_argument("card")
    submit.add_argument("request_key", help="Постоянный ключ одного заказа записи")
    submit.add_argument("webhook", help="Публичный HTTPS-адрес обработчика")
    submit.add_argument("--audio", default=SAMPLE)
    sync = commands.add_parser("sync")
    sync.add_argument("id")
    commands.add_parser("notes")
    args = parser.parse_args()
    if args.command == "demo":
        demo()
        return
    if args.command in ("serve", "submit", "sync") and not os.environ.get("VOICEE_API_KEY"):
        parser.error("Передайте серверный ключ через переменную окружения VOICEE_API_KEY")
    db = open_crm("voicee-crm.sqlite3")
    try:
        if args.command == "serve":
            with HTTPServer(("127.0.0.1", 8765), Callback) as server:
                server.db = db
                server.serve_forever()
        elif args.command == "submit":
            job = api("POST", "/models/voicee/transcribe/predictions", {
                "input": {"audio": args.audio, "output_format": "text"},
                "webhook": args.webhook,
            }, args.request_key)
            with db:
                db.execute("INSERT INTO jobs VALUES (?, ?) ON CONFLICT(id) DO NOTHING",
                           (job["id"], args.card))
                card = db.execute("SELECT card FROM jobs WHERE id = ?", (job["id"],)).fetchone()[0]
                if card != args.card:
                    raise ValueError("Этот заказ уже привязан к другой карточке")
            print(job["id"])
        elif args.command == "sync":
            code = receive(db, {"id": args.id})
            if code == 404:
                parser.exit(1, "Привязка не найдена. Проверьте каталог базы и id из submit.\n")
            if code != 204:
                parser.exit(1, "Результат пока не подтверждён. Повторите sync с тем же id позже.\n")
            if db.execute("SELECT 1 FROM notes WHERE prediction_id = ?", (args.id,)).fetchone():
                print("Заметка сохранена.")
            else:
                print("Заказ завершён без расшифровки.")
        elif args.command == "notes":
            for row in db.execute("SELECT card, body FROM jobs JOIN notes ON prediction_id = jobs.id"):
                print(*row, sep=": ")
    except (OSError, ValueError, http.client.HTTPException, RuntimeError, sqlite3.Error) as exc:
        parser.exit(1, f"{exc}\n")
    finally:
        db.close()


if __name__ == "__main__":
    main()
