"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Live x402 demo: a paid API and an agent-side client paying for it
 * with real KAS on testnet-10.
 *
 * Flow demonstrated:
 *   1. First request -> 402 with a kaspa-tab offer
 *   2. Client deposits (policy-gated, on-chain, ~1s confirmation)
 *   3. Request retried and served, charged against the tab
 *   4. Further requests served instantly with zero on-chain cost
 *
 * Usage: SOMPI_NODE_URL=<node> npm run build && node dist/demo-x402.js
 */
const http = __importStar(require("node:http"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const policy_1 = require("./policy");
const wallet_1 = require("./wallet");
const client_1 = require("./x402/client");
const server_1 = require("./x402/server");
const NETWORK = process.env.SOMPI_NETWORK ?? "testnet-10";
const PORT = 8642;
const JOKES = [
    "Why did the UTXO cross the DAG? To get to the other tip.",
    "I'd tell you a storage mass joke, but it's too dusty.",
    "10 blocks per second walk into a bar. The bar reorgs.",
];
async function main() {
    // --- the seller: a paid API ---
    const sellerWallet = new wallet_1.KaspaWallet({
        networkId: NETWORK,
        dataDir: path.join(os.homedir(), ".sompi", NETWORK, "demo-seller"),
        nodeUrl: process.env.SOMPI_NODE_URL,
    });
    const tabs = new server_1.TabServer({
        networkId: NETWORK,
        rpc: () => sellerWallet.client(),
        minDepositSompi: 100000000n, // 1 KAS tab deposit
        pricePerRequestSompi: 1000n, // 0.00001 KAS per request
        dataDir: path.join(os.homedir(), ".sompi", NETWORK, "demo-seller"),
        description: "sompi demo: jokes, 1000 sompi each",
    });
    let served = 0;
    const server = http.createServer(async (req, res) => {
        try {
            if (await tabs.gate(req, res))
                return; // answered with 402
            res.setHeader("content-type", "application/json");
            res.end(JSON.stringify({ joke: JOKES[served++ % JOKES.length] }));
        }
        catch (e) {
            res.statusCode = 500;
            res.end(JSON.stringify({ error: String(e) }));
        }
    });
    await new Promise((r) => server.listen(PORT, r));
    console.log(`[seller] paid API listening on :${PORT} (1000 sompi/request, 1 KAS min deposit)`);
    // --- the buyer: an agent's wallet + policy + x402 client ---
    const buyerWallet = new wallet_1.KaspaWallet({
        networkId: NETWORK,
        dataDir: path.join(os.homedir(), ".sompi", NETWORK),
        nodeUrl: process.env.SOMPI_NODE_URL,
    });
    const policy = new policy_1.PolicyEngine(path.join(os.homedir(), ".sompi", NETWORK));
    const client = new client_1.X402Client(buyerWallet, policy, path.join(os.homedir(), ".sompi", NETWORK));
    console.log(`[buyer]  wallet ${buyerWallet.address}`);
    console.log(`[buyer]  balance ${(0, wallet_1.formatKas)(await buyerWallet.balanceSompi())} KAS\n`);
    for (let i = 1; i <= 3; i++) {
        const t0 = Date.now();
        const result = await client.paidFetch(`http://127.0.0.1:${PORT}/api/joke`);
        const ms = Date.now() - t0;
        console.log(`request ${i} (${ms}ms): HTTP ${result.status} ${result.body}`);
        if (result.deposit) {
            console.log(`          paid on-chain deposit: ${(0, wallet_1.formatKas)(BigInt(result.deposit.amountSompi))} KAS, txid ${result.deposit.txid}`);
        }
        if (result.remainingSompi) {
            console.log(`          tab remaining: ${result.remainingSompi} sompi`);
        }
    }
    console.log(`\n[buyer]  final balance ${(0, wallet_1.formatKas)(await buyerWallet.balanceSompi())} KAS`);
    server.close();
    await buyerWallet.disconnect();
    await sellerWallet.disconnect();
    process.exit(0);
}
main().catch((e) => {
    console.error("demo failed:", e);
    process.exit(1);
});
