"""Sim7 reference integration. Python 3.10+, standard library only.
SQLite state must live on persistent private storage. Never run two resellers
against different state files for the same business operation.
"""
import argparse
import hashlib
import hmac
import http.client
import json
import math
import os
import re
import sqlite3
import time
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

TERMINAL = {"completed", "cancelled", "banned", "expired"}
EVENTS = {"order.created", "order.code_received", "order.completed", "order.cancelled", "order.banned", "order.expired"}
MAX_AGE = 6 * 86400  # Stop before the API's seven-day replay retention boundary.


class Sim7Error(Exception):
    def __init__(self, code, status=0):
        self.code, self.status = code, status
        super().__init__(f"Sim7 {code} (HTTP {status}); keep the original business ID")


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *_args, **_kwargs):
        return None  # Do not forward a bearer key to a redirect destination.


def canonical(value):
    def normalize(item):
        if isinstance(item, float) and item.is_integer():
            return int(item)  # CLI 1.0 and library 1 are the same price.
        if isinstance(item, dict):
            return {key: normalize(val) for key, val in item.items()}
        if isinstance(item, (list, tuple)):
            return [normalize(val) for val in item]
        return item
    return json.dumps(normalize(value), sort_keys=True, separators=(",", ":"), allow_nan=False)


class State:
    def __init__(self, path):
        self.db = sqlite3.connect(path, timeout=10)
        if path != ":memory:":
            os.chmod(path, 0o600)
        self.db.execute("PRAGMA synchronous=FULL")
        self.db.executescript("""
          CREATE TABLE IF NOT EXISTS intents(scope TEXT, id TEXT, credential TEXT NOT NULL, payload TEXT NOT NULL,
            created REAL NOT NULL, receipt TEXT, PRIMARY KEY(scope,id));
          CREATE TABLE IF NOT EXISTS inbox(id TEXT PRIMARY KEY, body TEXT NOT NULL,
            received REAL NOT NULL, processed INTEGER NOT NULL DEFAULT 0);
        """)

    def intent(self, scope, business_id, payload, credential):
        if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{7,99}", business_id):
            raise ValueError("business_id: use 8-100 safe characters from your own order system")
        encoded = canonical(payload)
        with self.db:
            self.db.execute("INSERT OR IGNORE INTO intents VALUES(?,?,?,?,?,NULL)", (scope, business_id, credential, encoded, time.time()))
        row = self.db.execute("SELECT payload,created,receipt,credential FROM intents WHERE scope=? AND id=?", (scope, business_id)).fetchone()
        if row[0] != encoded:
            raise Sim7Error("local_idempotency_conflict")
        if row[2]:
            return json.loads(row[2])
        if row[3] != credential:
            raise Sim7Error("unresolved_intent_uses_another_api_key")
        if time.time() - row[1] >= MAX_AGE:
            raise Sim7Error("unresolved_intent_too_old_contact_support")
        return None

    def save(self, scope, business_id, receipt):
        with self.db:
            self.db.execute("UPDATE intents SET receipt=? WHERE scope=? AND id=?", (canonical(receipt), scope, business_id))

    def accept_event(self, event, raw):
        # Durable inbox only. A separate business worker handles pending rows.
        # Its side effects and processed=1 must share the business transaction.
        with self.db:
            self.db.execute("INSERT OR IGNORE INTO inbox(id,body,received) VALUES(?,?,?)", (event["id"], raw.decode("utf-8"), time.time()))

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


class Client:
    def __init__(self, token, state, base_url="https://sim7.org/api/v1", *, allow_loopback=False, attempts=3, sleep=time.sleep):
        url = urllib.parse.urlsplit(base_url)
        local = allow_loopback and url.scheme == "http" and url.hostname in {"127.0.0.1", "::1", "localhost"}
        if (url.scheme != "https" and not local) or not url.netloc or url.username or url.password or url.query or url.fragment:
            raise ValueError("An HTTPS API URL without credentials, query or fragment is required")
        if not token or "\n" in token or "\r" in token:
            raise ValueError("Set SIM7_API_KEY to your private live key")
        self.base, self.token, self.state = base_url.rstrip("/"), token, state
        self.scope = None
        self.credential = hashlib.sha256(token.encode()).hexdigest()
        self.opener = urllib.request.build_opener(NoRedirect())
        self.attempts, self.sleep = max(1, min(attempts, 5)), sleep

    def request(self, method, path, payload=None, key=None):
        if not path.startswith("/") or path.startswith("//"):
            raise ValueError("Use a relative API path")
        body = None if payload is None else canonical(payload).encode()
        headers = {"Authorization": "Bearer " + self.token, "Accept": "application/json"}
        if body is not None:
            headers["Content-Type"] = "application/json"
        if key:
            headers["Idempotency-Key"] = key
        for attempt in range(self.attempts):
            status, retry_after, code = 0, None, "network_uncertain"
            try:
                req = urllib.request.Request(self.base + path, data=body, headers=headers, method=method)
                try:
                    response = self.opener.open(req, timeout=20)
                except urllib.error.HTTPError as error:
                    response = error
                with response:
                    status = response.code
                    retry_after = response.headers.get("Retry-After")
                    raw = response.read(2 * 1024 * 1024 + 1)
                if len(raw) > 2 * 1024 * 1024:
                    raise Sim7Error("response_too_large", status)
                try:
                    parsed = json.loads(raw)
                except (ValueError, UnicodeError):
                    parsed = {}
                if 200 <= status < 300 and isinstance(parsed, dict) and "data" in parsed:
                    return parsed["data"]
                error = parsed.get("error") if isinstance(parsed, dict) else None
                code = error.get("code", "invalid_response") if isinstance(error, dict) else "invalid_response"
                if not isinstance(code, str):
                    code = "invalid_response"
                retry = status == 429 or status >= 500 or code == "idempotency_in_progress" or (200 <= status < 300)
                if not retry:
                    raise Sim7Error(code, status)
            except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException):
                pass
            if attempt + 1 == self.attempts:
                raise Sim7Error(code, status)
            delay = min(2 ** attempt, 10)
            if retry_after:
                # Never retry earlier than the provider's requested delay.
                if not retry_after.isdigit() or int(retry_after) > 120:
                    raise Sim7Error("retry_later_same_business_id", status)
                delay = max(delay, int(retry_after))
            self.sleep(delay)

    def purchase(self, business_id, service, country, max_price, operator="any"):
        if not isinstance(max_price, (int, float)) or isinstance(max_price, bool) or not math.isfinite(max_price) or max_price <= 0:
            raise ValueError("max_price is a positive USD number, not rubles")
        payload = {"service": service, "country": country, "operator": operator, "max_price": max_price}
        if self.scope is None:
            account = self.request("GET", "/account")
            if not isinstance(account, dict) or not isinstance(account.get("account_id"), str) or not account["account_id"]:
                raise Sim7Error("invalid_account_response")
            self.scope = hashlib.sha256((self.base + "\n" + account["account_id"]).encode()).hexdigest()
        cached = self.state.intent(self.scope, business_id, payload, self.credential)
        if cached is not None:
            return cached
        key = "purchase:" + hashlib.sha256(business_id.encode()).hexdigest()
        order = self.request("POST", "/numbers", payload, key)
        if not isinstance(order, dict) or not re.fullmatch(r"ord_[A-Za-z0-9_-]{22}", order.get("order_id", "")):
            raise Sim7Error("invalid_purchase_receipt")
        self.state.save(self.scope, business_id, order)
        return order

    def get_order(self, order_id):
        if not re.fullmatch(r"ord_[A-Za-z0-9_-]{22}", order_id):
            raise ValueError("Use the Sim7 order_id, not the phone number")
        return self.request("GET", "/orders/" + order_id)

    def watch(self, order_id, seconds=1200, interval=5):
        end, seen, previous = time.monotonic() + seconds, set(), None
        while time.monotonic() < end:
            order = self.get_order(order_id)
            new = []
            for index, message in enumerate(order.get("messages", [])):
                identity = canonical([index, message])
                if identity not in seen:
                    seen.add(identity)
                    new.append(message)
            if new or order["status"] != previous:
                yield {"order": order, "new_messages": new}
            previous = order["status"]
            if order["status"] in TERMINAL:
                return
            self.sleep(interval)  # code_received stays active; never auto-finish.

    def action(self, order_id, action):
        if action not in {"finish", "cancel", "ban"} or not re.fullmatch(r"ord_[A-Za-z0-9_-]{22}", order_id):
            raise ValueError("Invalid explicit order action")
        key = action + ":" + hashlib.sha256(order_id.encode()).hexdigest()
        return self.request("POST", f"/orders/{order_id}/{action}", key=key)


def verify_webhook(raw, headers, secrets, now=None):
    headers = {key.lower(): value for key, value in headers.items()}
    timestamp, signature = headers.get("x-sim7-timestamp", ""), headers.get("x-sim7-signature", "")
    secret = secrets.get(headers.get("x-sim7-secret-version", ""))
    if len(raw) > 65536 or not secret or not re.fullmatch(r"\d{1,12}", timestamp) or not re.fullmatch(r"v1=[a-f0-9]{64}", signature):
        raise ValueError("Invalid webhook")
    if abs((time.time() if now is None else now) - int(timestamp)) > 300:
        raise ValueError("Expired webhook timestamp")
    expected = "v1=" + hmac.new(secret.encode(), timestamp.encode() + b"." + raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signature):
        raise ValueError("Invalid signature")
    event = json.loads(raw)
    if not isinstance(event, dict) or not isinstance(event.get("id"), str) or not event["id"] or len(event["id"]) > 200 or event.get("event") not in EVENTS or not isinstance(event.get("data"), dict):
        raise ValueError("Invalid event")
    if event["id"] != headers.get("x-sim7-delivery") or event["event"] != headers.get("x-sim7-event"):
        raise ValueError("Header/body mismatch")
    return event


def webhook_server(state, secrets, port=8080):
    class Handler(BaseHTTPRequestHandler):
        def do_POST(self):
            if self.path != "/webhooks/sim7":
                self.send_error(404); return
            length = self.headers.get("Content-Length", "")
            if not length.isdigit() or not 0 < int(length) <= 65536 or self.headers.get("Transfer-Encoding"):
                self.send_error(413); return
            self.connection.settimeout(10)
            try:
                raw = self.rfile.read(int(length))
                if len(raw) != int(length):
                    raise ValueError("Incomplete body")
                event = verify_webhook(raw, dict(self.headers), secrets)
            except (ValueError, OSError, UnicodeError):
                self.send_error(401); return
            try:
                state.accept_event(event, raw)
            except sqlite3.Error:
                self.send_error(503); return  # Do not acknowledge a failed write.
            self.send_response(200); self.end_headers(); self.wfile.write(b"ok")

        def log_message(self, *_args):
            pass  # Do not log phone numbers, SMS bodies or signing headers.
    return HTTPServer(("127.0.0.1", port), Handler)


def main():
    parser = argparse.ArgumentParser(description="Sim7 live API reference client")
    parser.add_argument("command", choices=["balance", "prices", "buy", "watch", "finish", "cancel", "ban", "webhook"])
    parser.add_argument("--business-id"); parser.add_argument("--service"); parser.add_argument("--country")
    parser.add_argument("--operator", default="any"); parser.add_argument("--max-price", type=float)
    parser.add_argument("--order-id"); parser.add_argument("--seconds", type=int, default=1200)
    parser.add_argument("--confirm", action="store_true"); parser.add_argument("--show-messages", action="store_true")
    parser.add_argument("--port", type=int, default=8080)
    args = parser.parse_args()
    os.umask(0o077)
    state = State(os.environ.get("SIM7_STATE_FILE", "sim7-state.sqlite"))
    if args.command == "webhook":
        secrets = json.loads(os.environ["SIM7_WEBHOOK_SECRETS"])
        if not isinstance(secrets, dict) or not secrets or not all(isinstance(v, str) and len(v) >= 16 for v in secrets.values()):
            parser.error("SIM7_WEBHOOK_SECRETS must map secret versions to signing secrets")
        webhook_server(state, secrets, args.port).serve_forever(); return
    client = Client(os.environ.get("SIM7_API_KEY", ""), state)
    if args.command == "balance":
        result = client.request("GET", "/balance")
    elif args.command == "prices":
        if not args.service:
            parser.error("--service is required")
        result = client.request("GET", "/prices?" + urllib.parse.urlencode({"service": args.service, **({"country": args.country} if args.country else {})}))
    elif args.command == "buy":
        if not args.confirm or not all([args.business_id, args.service, args.country, args.max_price]):
            parser.error("buy requires --confirm --business-id --service --country --max-price (USD)")
        order = client.purchase(args.business_id, args.service, args.country, args.max_price, args.operator)
        result = {k: order.get(k) for k in ["order_id", "number", "status", "price", "expires_at"]}
    elif args.command == "watch":
        if not args.order_id or not 1 <= args.seconds <= 86400:
            parser.error("watch requires --order-id and --seconds between 1 and 86400")
        for update in client.watch(args.order_id, args.seconds):
            result = {"order_id": args.order_id, "status": update["order"]["status"], "new_message_count": len(update["new_messages"])}
            if args.show_messages:
                result["new_messages"] = update["new_messages"]
            print(json.dumps(result), flush=True)
        return
    else:
        if not args.confirm or not args.order_id:
            parser.error("order actions require --order-id and --confirm")
        result = client.action(args.order_id, args.command)
        result = {k: result.get(k) for k in ["order_id", "status"]}
    print(json.dumps(result))


if __name__ == "__main__":
    try:
        main()
    except (Sim7Error, ValueError, KeyError) as error:
        # No raw remote response or exception traceback with credentials.
        print(str(error) if isinstance(error, Sim7Error) else "Invalid configuration or input", file=__import__("sys").stderr)
        raise SystemExit(1)
