"""Independent fictional merchant: current ACL, approvals, fencing and receipts.

The service alone commits returns. Agent checkpoints cannot manufacture receipts.
Demo bearer tokens identify seeded sessions; no client supplied tenant/user is trusted.
"""
import argparse
import json
import socket
import sqlite3
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
from common import LabError, canonical, connect, digest, now

TOKENS = {"alice-token": "alice", "bob-token": "bob", "other-token": "other",
          "reviewer-token": "reviewer", "admin-token": "admin"}
POLICIES = [
    ("d-general", "ordinary", "Unused ordinary items may be returned within 30 days of delivery. Create a return application, not a refund."),
    ("d-battery", "battery", "Battery items need manual safety review. Do not create an automatic return application even within 30 days."),
    ("d-proof", "proof", "Return applications require the current user's own order, a stated reason and an approved quantity no greater than the purchased quantity.")]


def init(path):
    db = connect(path)
    db.executescript("""
    CREATE TABLE IF NOT EXISTS users(id TEXT PRIMARY KEY,tenant TEXT,role TEXT,active INTEGER,auth_version INTEGER);
    CREATE TABLE IF NOT EXISTS orders(id TEXT PRIMARY KEY,tenant TEXT,owner TEXT,kind TEXT,quantity INTEGER,age_days INTEGER);
    CREATE TABLE IF NOT EXISTS tenant_policy(tenant TEXT PRIMARY KEY,version INTEGER);
    CREATE TABLE IF NOT EXISTS policies(tenant TEXT,version INTEGER,id TEXT,kind TEXT,text TEXT,PRIMARY KEY(tenant,version,id));
    CREATE TABLE IF NOT EXISTS memories(owner TEXT PRIMARY KEY,version INTEGER,value TEXT,expires REAL,active INTEGER);
    CREATE TABLE IF NOT EXISTS approvals(id TEXT PRIMARY KEY,task_id TEXT,tenant TEXT,owner TEXT,proposal_hash TEXT,proposal_version INTEGER,reviewer TEXT,expires REAL,revoked INTEGER);
    CREATE TABLE IF NOT EXISTS claims(task_id TEXT PRIMARY KEY,tenant TEXT,owner TEXT,fence INTEGER,cancelled INTEGER DEFAULT 0);
    CREATE TABLE IF NOT EXISTS returns(id TEXT PRIMARY KEY,task_id TEXT UNIQUE,tenant TEXT,owner TEXT,order_id TEXT,quantity INTEGER,proposal_hash TEXT);
    CREATE TABLE IF NOT EXISTS receipts(operation_key TEXT PRIMARY KEY,request_hash TEXT,tenant TEXT,owner TEXT,task_id TEXT,result_json TEXT,created REAL);
    """)
    for user, tenant, role in [("alice", "acme", "user"), ("bob", "acme", "user"),
                               ("other", "other", "user"), ("reviewer", "acme", "reviewer"), ("admin", "acme", "admin")]:
        db.execute("INSERT OR IGNORE INTO users VALUES(?,?,?,1,1)", (user, tenant, role))
    for row in [("o-100", "acme", "alice", "ordinary", 2, 8),
                ("o-battery", "acme", "alice", "battery", 1, 5),
                ("o-gift", "acme", "alice", "gift", 1, 8),
                ("o-old", "acme", "alice", "ordinary", 1, 40),
                ("o-bob", "acme", "bob", "ordinary", 1, 7),
                ("o-other", "other", "other", "ordinary", 1, 7)]:
        db.execute("INSERT OR IGNORE INTO orders VALUES(?,?,?,?,?,?)", row)
    for tenant in ["acme", "other"]:
        db.execute("INSERT OR IGNORE INTO tenant_policy VALUES(?,1)", (tenant,))
        for policy_id, kind, text in POLICIES:
            db.execute("INSERT OR IGNORE INTO policies VALUES(?,1,?,?,?)", (tenant, policy_id, kind, text))
    for owner in ["alice", "bob", "other"]:
        db.execute("INSERT OR IGNORE INTO memories VALUES(?,1,?,?,1)",
                   (owner, canonical({"language": "en", "source": "user_confirmed_demo_preference"}), now() + 86400))
    db.close()


def principal(db, token):
    row = db.execute("SELECT * FROM users WHERE id=?", (TOKENS.get(token, ""),)).fetchone()
    if not row or not row["active"]:
        raise LabError("permission_denied", 403)
    return dict(row)


def owned_order(db, actor, order_id):
    order = db.execute("SELECT * FROM orders WHERE id=? AND tenant=? AND owner=?",
                       (order_id, actor["tenant"], actor["id"])).fetchone()
    if not order:
        raise LabError("order_permission_denied", 403)
    return dict(order)


def memory(db, owner):
    row = dict(db.execute("SELECT * FROM memories WHERE owner=?", (owner,)).fetchone())
    row["value"] = json.loads(row["value"]) if row["active"] and row["expires"] > now() else None
    row["usable"] = row["value"] is not None
    return row


def check_proposal(db, actor, p):
    keys = {"action", "order_id", "reason", "quantity", "policy_version", "policy_ids", "memory_version", "version"}
    if not isinstance(p, dict) or set(p) != keys or p["action"] != "create_return":
        raise LabError("invalid_action", 400)
    if any(type(p[k]) is not int or p[k] < 1 for k in ["quantity", "policy_version", "memory_version", "version"]):
        raise LabError("invalid_parameters", 400)
    if not isinstance(p["reason"], str) or not 1 <= len(p["reason"].strip()) <= 500:
        raise LabError("invalid_reason", 400)
    if not isinstance(p["policy_ids"], list) or not all(isinstance(i, str) for i in p["policy_ids"]):
        raise LabError("invalid_evidence", 400)
    order = owned_order(db, actor, p["order_id"])
    if p["quantity"] > order["quantity"]:
        raise LabError("invalid_quantity", 400)
    current = db.execute("SELECT version FROM tenant_policy WHERE tenant=?", (actor["tenant"],)).fetchone()[0]
    if current != p["policy_version"]:
        raise LabError("policy_changed")
    current_memory = memory(db, actor["id"])
    if current_memory["version"] != p["memory_version"] or not current_memory["usable"]:
        raise LabError("memory_changed_or_expired")
    required = {"d-general", "d-proof"}
    policies = {row["id"]: dict(row) for row in db.execute("SELECT * FROM policies WHERE tenant=? AND version=?", (actor["tenant"], current))}
    if order["kind"] == "battery" or order["age_days"] > 30:
        raise LabError("manual_review_required")
    if order["kind"] == "gift" and "d-gift" in policies:
        raise LabError("manual_review_required")
    if not required.issubset(p["policy_ids"]) or not set(p["policy_ids"]).issubset(policies):
        raise LabError("missing_policy_evidence")
    return order


def route(db, token, method, path, body):
    actor = principal(db, token)
    parts = path.strip("/").split("/")
    if method == "GET" and path == "/v1/me":
        return actor
    if method == "GET" and parts[:2] == ["v1", "orders"] and len(parts) == 3:
        return owned_order(db, actor, parts[2])
    if method == "GET" and path == "/v1/policies":
        version = db.execute("SELECT version FROM tenant_policy WHERE tenant=?", (actor["tenant"],)).fetchone()[0]
        return {"tenant": actor["tenant"], "version": version, "documents":
                [dict(r) for r in db.execute("SELECT * FROM policies WHERE tenant=? AND version=? ORDER BY id", (actor["tenant"], version))]}
    if path == "/v1/memory" and actor["role"] == "user":
        if method == "GET":
            return memory(db, actor["id"])
        if method in {"PUT", "DELETE"}:
            value = body.get("value", {}) if method == "PUT" else {}
            ttl = body.get("ttl_seconds", 3600)
            if set(value) - {"language"} or value.get("language", "en") not in {"en", "zh"} or type(ttl) not in {int, float} or not 0 < ttl <= 86400:
                raise LabError("invalid_memory", 400)
            db.execute("UPDATE memories SET version=version+1,value=?,expires=?,active=? WHERE owner=?",
                       (canonical(value), now() + ttl, int(method == "PUT"), actor["id"]))
            return memory(db, actor["id"])
    if method == "POST" and path == "/v1/approvals":
        if actor["role"] != "reviewer":
            raise LabError("reviewer_required", 403)
        p = body["proposal"]
        owner = dict(db.execute("SELECT * FROM users WHERE id=? AND tenant=? AND active=1", (body["owner_id"], actor["tenant"])).fetchone() or {})
        if not owner:
            raise LabError("permission_denied", 403)
        check_proposal(db, owner, p)
        if body["proposal_hash"] != digest(p) or body["expected_version"] != p["version"]:
            raise LabError("approval_binding_mismatch")
        ttl = body.get("ttl_seconds", 300)
        if type(ttl) not in {int, float} or not 0 < ttl <= 3600:
            raise LabError("invalid_approval_expiry", 400)
        approval_id = "ap-" + uuid.uuid4().hex[:16]
        db.execute("INSERT INTO approvals VALUES(?,?,?,?,?,?,?,?,0)",
                   (approval_id, body["task_id"], actor["tenant"], owner["id"], digest(p), p["version"], actor["id"], now() + ttl))
        return {"approval_id": approval_id, "proposal_hash": digest(p), "proposal_version": p["version"], "expires": now() + ttl}
    if method == "POST" and path == "/v1/claims":
        if actor["role"] != "user" or type(body["fence"]) is not int or body["fence"] < 1:
            raise LabError("invalid_claim", 400)
        row = db.execute("SELECT * FROM claims WHERE task_id=?", (body["task_id"],)).fetchone()
        if row and (row["tenant"] != actor["tenant"] or row["owner"] != actor["id"]):
            raise LabError("permission_denied", 403)
        if row and row["cancelled"]:
            raise LabError("task_cancelled")
        if row and row["fence"] > body["fence"]:
            raise LabError("stale_fence")
        db.execute("INSERT INTO claims VALUES(?,?,?,?,0) ON CONFLICT(task_id) DO UPDATE SET fence=excluded.fence",
                   (body["task_id"], actor["tenant"], actor["id"], body["fence"]))
        return {"task_id": body["task_id"], "fence": body["fence"]}
    if method == "GET" and parts[:2] == ["v1", "claims"] and len(parts) == 3:
        row = db.execute("SELECT * FROM claims WHERE task_id=?", (parts[2],)).fetchone()
        if row and (row["tenant"] != actor["tenant"] or row["owner"] != actor["id"]):
            raise LabError("permission_denied", 403)
        return {"fence": row["fence"] if row else 0, "cancelled": bool(row and row["cancelled"])}
    if method == "POST" and path == "/v1/cancel":
        task_id = body["task_id"]
        claim = db.execute("SELECT * FROM claims WHERE task_id=?", (task_id,)).fetchone()
        if claim and (claim["tenant"] != actor["tenant"] or claim["owner"] != actor["id"]):
            raise LabError("permission_denied", 403)
        db.execute("INSERT INTO claims VALUES(?,?,?,0,1) ON CONFLICT(task_id) DO UPDATE SET cancelled=1", (task_id, actor["tenant"], actor["id"]))
        receipt = db.execute("SELECT result_json FROM receipts WHERE task_id=? AND tenant=? AND owner=?", (task_id, actor["tenant"], actor["id"])).fetchone()
        return {"cancelled": True, "committed_receipt": json.loads(receipt[0]) if receipt else None}
    if method == "POST" and path == "/v1/returns":
        p, task_id = body["proposal"], body["task_id"]
        if type(body["fence"]) is not int or not isinstance(body["operation_key"], str) or not 1 <= len(body["operation_key"]) <= 200:
            raise LabError("invalid_action_binding", 400)
        if body["proposal_hash"] != digest(p):
            raise LabError("proposal_hash_mismatch")
        binding = {k: body[k] for k in ["task_id", "proposal", "proposal_hash", "approval_id", "operation_key"]}
        request_hash = digest(binding)
        claim = db.execute("SELECT * FROM claims WHERE task_id=?", (task_id,)).fetchone()
        if not claim or claim["tenant"] != actor["tenant"] or claim["owner"] != actor["id"]:
            raise LabError("claim_required", 403)
        if body["fence"] != claim["fence"]:
            raise LabError("stale_fence")
        existing = db.execute("SELECT * FROM receipts WHERE operation_key=?", (body["operation_key"],)).fetchone()
        if existing:
            if existing["tenant"] != actor["tenant"] or existing["owner"] != actor["id"]:
                raise LabError("permission_denied", 403)
            if existing["request_hash"] != request_hash:
                raise LabError("idempotency_conflict")
            return json.loads(existing["result_json"])
        if claim["cancelled"]:
            raise LabError("task_cancelled")
        order = check_proposal(db, actor, p)  # Recheck CURRENT authorization/policy/memory, inside this transaction.
        approval = db.execute("SELECT * FROM approvals WHERE id=?", (body["approval_id"],)).fetchone()
        if not approval or approval["task_id"] != task_id or approval["tenant"] != actor["tenant"] or approval["owner"] != actor["id"] or approval["proposal_hash"] != digest(p) or approval["proposal_version"] != p["version"]:
            raise LabError("approval_binding_mismatch")
        if approval["revoked"] or approval["expires"] <= now():
            raise LabError("approval_expired_or_revoked")
        reviewer = db.execute("SELECT * FROM users WHERE id=? AND active=1 AND role='reviewer' AND tenant=?", (approval["reviewer"], actor["tenant"])).fetchone()
        if not reviewer:
            raise LabError("reviewer_revoked", 403)
        if db.execute("SELECT 1 FROM returns WHERE task_id=?", (task_id,)).fetchone():
            raise LabError("task_already_has_return")
        return_id = "ret-" + uuid.uuid4().hex[:16]
        result = {"return_id": return_id, "task_id": task_id, "order_id": order["id"], "quantity": p["quantity"], "proposal_hash": digest(p), "operation_key": body["operation_key"], "status": "application_created"}
        db.execute("INSERT INTO returns VALUES(?,?,?,?,?,?,?)", (return_id, task_id, actor["tenant"], actor["id"], order["id"], p["quantity"], digest(p)))
        db.execute("INSERT INTO receipts VALUES(?,?,?,?,?,?,?)", (body["operation_key"], request_hash, actor["tenant"], actor["id"], task_id, canonical(result), now()))
        return result
    if method == "GET" and parts[:2] == ["v1", "receipts"] and len(parts) == 3:
        row = db.execute("SELECT * FROM receipts WHERE operation_key=? AND tenant=? AND owner=?", (parts[2], actor["tenant"], actor["id"])).fetchone()
        return {"found": bool(row), "receipt": json.loads(row["result_json"]) if row else None}
    if method == "GET" and path == "/v1/audit":
        if actor["role"] != "admin":
            raise LabError("admin_required", 403)
        return {"returns": [dict(r) for r in db.execute("SELECT * FROM returns WHERE tenant=? ORDER BY task_id", (actor["tenant"],))],
                "receipt_count": db.execute("SELECT count(*) FROM receipts WHERE tenant=?", (actor["tenant"],)).fetchone()[0]}
    if method == "POST" and path == "/v1/admin/revoke-user":
        if actor["role"] != "admin":
            raise LabError("admin_required", 403)
        db.execute("UPDATE users SET active=?,auth_version=auth_version+1 WHERE id=? AND tenant=? AND role='user'", (int(body.get("active", False)), body["user_id"], actor["tenant"]))
        return {"updated": True}
    if method == "POST" and path == "/v1/admin/revoke-reviewer":
        if actor["role"] != "admin":
            raise LabError("admin_required", 403)
        db.execute("UPDATE users SET active=?,auth_version=auth_version+1 WHERE id=? AND tenant=? AND role='reviewer'", (int(body.get("active", False)), body["user_id"], actor["tenant"]))
        return {"updated": True}
    if method == "POST" and path == "/v1/admin/policy-exception":
        if actor["role"] != "admin" or body.get("kind") != "gift":
            raise LabError("invalid_policy_extension", 403)
        old = db.execute("SELECT version FROM tenant_policy WHERE tenant=?", (actor["tenant"],)).fetchone()[0]
        version = old + 1
        db.execute("INSERT INTO policies SELECT tenant,?,id,kind,text FROM policies WHERE tenant=? AND version=?", (version, actor["tenant"], old))
        db.execute("INSERT OR REPLACE INTO policies VALUES(?,?,'d-gift','gift',?)", (actor["tenant"], version, "Gift items require manual review and proof of purchase; do not create automatic return applications."))
        db.execute("UPDATE tenant_policy SET version=? WHERE tenant=?", (version, actor["tenant"]))
        return {"policy_version": version, "exception_id": "d-gift"}
    if method == "POST" and path == "/v1/admin/policy-bump":
        if actor["role"] != "admin":
            raise LabError("admin_required", 403)
        old = db.execute("SELECT version FROM tenant_policy WHERE tenant=?", (actor["tenant"],)).fetchone()[0]
        db.execute("INSERT INTO policies SELECT tenant,?,id,kind,text FROM policies WHERE tenant=? AND version=?", (old + 1, actor["tenant"], old))
        db.execute("UPDATE tenant_policy SET version=? WHERE tenant=?", (old + 1, actor["tenant"]))
        return {"policy_version": old + 1}
    if method == "POST" and path == "/v1/admin/revoke-approval":
        if actor["role"] != "admin":
            raise LabError("admin_required", 403)
        db.execute("UPDATE approvals SET revoked=1 WHERE id=? AND tenant=?", (body["approval_id"], actor["tenant"]))
        return {"revoked": True}
    raise LabError("not_found", 404)


def server(path, host="127.0.0.1", port=8789):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *_):
            pass

        def handle_request(self):
            db = None
            try:
                if self.path == "/health" and self.command == "GET":
                    result = {"ok": True, "service": "fictional-merchant"}
                else:
                    size = int(self.headers.get("Content-Length", "0"))
                    if size > 65536:
                        raise LabError("body_too_large", 413)
                    body = json.loads(self.rfile.read(size)) if size else {}
                    db = connect(path)
                    db.execute("BEGIN IMMEDIATE")
                    result = route(db, self.headers.get("Authorization", "").removeprefix("Bearer "), self.command, urlparse(self.path).path, body)
                    db.commit()
                if self.headers.get("X-Lab-Drop-Response") == "1" and self.path == "/v1/returns":
                    self.connection.shutdown(socket.SHUT_RDWR)
                    self.connection.close()  # Business commit completed, HTTP response deliberately lost.
                    return
                status = 200
            except LabError as exc:
                if db:
                    db.rollback()
                result, status = {"error": exc.code}, exc.status
            except (ValueError, KeyError, TypeError, sqlite3.Error):
                if db:
                    db.rollback()
                result, status = {"error": "invalid_request"}, 400
            finally:
                if db:
                    db.close()
            data = canonical(result).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        do_GET = do_POST = do_PUT = do_DELETE = handle_request
    return ThreadingHTTPServer((host, port), Handler)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("command", choices=["init", "serve"])
    parser.add_argument("--db", default="work/merchant.sqlite")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8789)
    args = parser.parse_args()
    init(args.db)
    if args.command == "serve":
        server(args.db, args.host, args.port).serve_forever()
    else:
        print(canonical({"initialized": args.db, "fictional_data": True}))
