"""Backend-only Get SMS client. No request is made merely by importing this file.
Set GETSMS_API_KEY in your server environment. Keep the SQLite intent file private,
backed up, and on persistent storage. Use a unique reference for each approved sale.
No SMS, API key, phone number or response body is written to this intent database.
"""
import http.client
import re
import json
import os
import random
import sqlite3
import time
import uuid
import urllib.error
import urllib.request

BASE = "https://get-sms.io/api/v1"


class APIError(Exception):
    def __init__(self, status, code, retry_after=0):
        super().__init__(f"Get SMS HTTP {status}: {code}")
        self.status, self.code, self.retry_after = status, code, retry_after


class ProtocolError(Exception):
    """An ambiguous/unusable response. Never include response data in the error."""


ORDER_STATES = {"created", "purchasing", "pending", "received", "reconciliation",
                "finished", "cancelled", "timeout", "banned", "failed"}


def response_data(payload, method, path):
    if not isinstance(payload, dict) or not isinstance(payload.get("data"), dict):
        raise ProtocolError("Invalid Get SMS response envelope; recover the same intent")
    data = payload["data"]
    if (method == "POST" and path == "/orders") or path.startswith(("/orders/", "/requests/")):
        try:
            valid_id = str(uuid.UUID(data["id"])) == data["id"].lower()
        except (KeyError, ValueError, TypeError, AttributeError):
            valid_id = False
        if (not valid_id or not isinstance(data.get("status"), str) or data["status"] not in ORDER_STATES
                or data.get("currency") != "USD"
                or not isinstance(data.get("price"), str)
                or not re.fullmatch(r"[0-9]+\.[0-9]{4}", data["price"])
                or not isinstance(data.get("sms"), list)):
            raise ProtocolError("Invalid Get SMS order; recover the same intent")
    return data


class Client:
    def __init__(self, intent_file, token=None):
        self.token = token or os.environ["GETSMS_API_KEY"]
        # Create privately; an existing database is never truncated.
        fd = os.open(intent_file, os.O_CREAT | os.O_RDWR, 0o600)
        os.close(fd)
        self.db = sqlite3.connect(intent_file)
        self.db.execute("CREATE TABLE IF NOT EXISTS intents (reference TEXT PRIMARY KEY, request_key TEXT UNIQUE NOT NULL, body TEXT NOT NULL)")
        self.db.commit()

    def request(self, method, path, body=None, request_key=None):
        headers = {"Authorization": "Bearer " + self.token, "Accept": "application/json"}
        raw = None
        if body is not None:
            headers["Content-Type"] = "application/json"
            raw = json.dumps(body).encode()
        if request_key:
            headers["Idempotency-Key"] = request_key
        req = urllib.request.Request(BASE + path, data=raw, method=method, headers=headers)
        try:
            with urllib.request.urlopen(req, timeout=120 if method == "POST" else 25) as response:
                return response_data(json.load(response), method, path)
        except urllib.error.HTTPError as error:
            try:
                payload = json.load(error).get("error", {})
            except (ValueError, AttributeError):
                payload = {}
            if not isinstance(payload, dict):
                payload = {}
            try:
                delay = int((error.headers or {}).get("Retry-After") or payload.get("retry_after") or 0)
            except (ValueError, TypeError):
                delay = 0
            # Deliberately do not expose/log raw server bodies or request headers.
            code = payload.get("code")
            if not isinstance(code, str) or not re.fullmatch(r"[A-Z][A-Z0-9_]{0,63}", code):
                code = "HTTP_ERROR"
            raise APIError(error.code, code, max(0, delay)) from None

    def intent(self, reference, approved_body):
        """The exact approved body is committed BEFORE any purchase request."""
        body = json.dumps(approved_body, sort_keys=True, separators=(",", ":"))
        with self.db:
            self.db.execute("INSERT OR IGNORE INTO intents VALUES (?, ?, ?)", (reference, str(uuid.uuid4()), body))
        key, saved = self.db.execute("SELECT request_key, body FROM intents WHERE reference=?", (reference,)).fetchone()
        if saved != body:
            raise ValueError("Reference already belongs to a different approved purchase")
        return key, json.loads(saved)

    def purchase(self, reference, approved_body, attempts=8):
        """Returns a recorded order, possibly still pending/reconciliation.
        On exhaustion, call again with the SAME reference and body. Never replace
        the reference merely because the outcome is unknown. No automatic rebuy.
        """
        key, body = self.intent(reference, approved_body)
        for attempt in range(attempts):
            try:
                try:
                    return self.request("GET", "/requests/" + key)
                except APIError as error:
                    if error.status != 404:
                        raise
                # A 404 does not prove the original request is finished. Reposting
                # the exact same durable intent is the safe recovery operation.
                return self.request("POST", "/orders", body, key)
            except APIError as error:
                if error.status != 429 and not 500 <= error.status <= 599:
                    raise  # 400/401/409/etc need explicit application decisions.
                delay = max(error.retry_after, min(30, 2 ** attempt))
            except (ProtocolError, http.client.HTTPException, urllib.error.URLError, TimeoutError, OSError, ValueError, KeyError):
                # A lost/malformed response may follow a committed purchase.
                delay = min(30, 2 ** attempt)
            time.sleep(delay + random.uniform(0, 1))
        raise RuntimeError("Outcome unresolved: resume the SAME reference/body; do not refund or create another intent")

    def stop_search(self, request_key):
        # Can be called by another worker while the original POST is still running.
        order = self.request("GET", "/requests/" + str(uuid.UUID(request_key)))
        return self.request("POST", "/orders/" + order["id"] + "/stop", {})

    def close(self):
        self.db.close()


def poll_interval(active_orders):
    """One account budget: >=5s/order, reserve 6 of 30 polls/min for retries.
    All workers must share ONE scheduler/rate limiter. Add per-order jitter and
    honor Retry-After; website use/other API clients may require more headroom.
    """
    return max(5, 60 * max(1, active_orders) / 24)
