import { create_txhex } from './tx.js';
import { now, sort_record } from './util.js';
import { DEFAULT_DEADLINE } from '../config.js';
import { init_vm } from '../vm/main.js';
import { get_path_names, get_path_vouts, get_proposal_id, } from './proposal.js';
export function create_contract(config) {
    const agent_fee = config.agent_fee;
    const feerate = config.feerate;
    const terms = config.proposal;
    const outputs = get_spend_outputs(terms, [agent_fee]);
    const published = config.published ?? now();
    const signatures = config.signatures ?? [];
    const subtotal = terms.value + agent_fee[0];
    const vout_size = outputs[0][1].length / 2;
    const txfee = vout_size * feerate;
    return sort_record({
        ...config.agent,
        activated: null,
        agent_fee: agent_fee,
        balance: 0,
        cid: config.cid,
        deadline: get_deadline(terms, published),
        est_txfee: txfee,
        est_txsize: vout_size,
        expires_at: null,
        feerate: feerate,
        moderator: config.moderator ?? null,
        outputs: get_spend_outputs(terms, [agent_fee]),
        pending: 0,
        prop_id: get_proposal_id(terms).hex,
        pubkeys: signatures.map(e => e.slice(0, 64)),
        published: published,
        settled: false,
        settled_at: null,
        signatures: signatures,
        spent: false,
        spent_at: null,
        spent_txid: null,
        status: 'published',
        subtotal: subtotal,
        terms: terms,
        total: subtotal + txfee,
        updated_at: published,
        vm_state: null,
        vout_size: vout_size
    });
}
export function activate_contract(contract, activated = now()) {
    const { cid, terms } = contract;
    const { expires, paths, programs, schedule } = terms;
    const pathnames = get_path_names(paths);
    return {
        ...contract,
        activated,
        expires_at: activated + expires,
        status: 'active',
        vm_state: init_vm({ activated, cid, pathnames, programs, schedule })
    };
}
function get_deadline(proposal, created) {
    const { deadline, effective } = proposal;
    if (effective !== undefined) {
        return effective - created;
    }
    else {
        return created + (deadline ?? DEFAULT_DEADLINE);
    }
}
export function get_spend_outputs(prop, fees) {
    const { payments, paths } = prop;
    const total_fees = [...payments, ...fees];
    const path_names = get_path_names(paths);
    const outputs = [];
    for (const name of path_names) {
        const vout = get_path_vouts(name, paths, total_fees);
        const txhex = create_txhex(vout);
        outputs.push([name, txhex]);
    }
    return outputs;
}
