import { Buff } from '@cmdcode/buff';
import { parse_addr } from '@scrow/tapscript/address';
import { create_vout } from '@scrow/tapscript/tx';
import { parse_program, parse_proposal } from './parse.js';
import { get_object_id, regex } from './util.js';
const GET_DEFAULT_PROP = () => {
    return {
        content: '',
        network: 'signet',
        members: [],
        paths: [],
        payments: [],
        programs: [],
        schedule: [],
        version: 1
    };
};
export function create_draft(template) {
    const { members = [], proposal, roles = [], signatures = [] } = template;
    const prop = create_proposal(proposal);
    return { members, proposal: prop, roles, signatures };
}
export function create_proposal(template) {
    return parse_proposal({ ...GET_DEFAULT_PROP(), ...template });
}
export function filter_path(label, paths) {
    return paths.filter(e => e[0] === label);
}
export function get_path_names(paths) {
    const pnames = new Set(paths.map(e => e[0]));
    return [...pnames].sort();
}
export function get_pay_total(payments) {
    return payments.map(e => e[0]).reduce((acc, curr) => acc + curr, 0);
}
export function get_addrs(paths) {
    const addrs = new Set(paths.map(e => e[2]));
    return [...addrs];
}
export function get_path_vouts(label, paths = [], payments = []) {
    const filtered = filter_path(label, paths).map(e => [e[1], e[2]]);
    const template = [...filtered.sort(), ...payments.sort()];
    return template.map(([value, addr]) => {
        const scriptPubKey = parse_addr(addr).asm;
        return create_vout({ value, scriptPubKey });
    });
}
export function get_path_total(paths) {
    const path_totals = [];
    const path_names = get_path_names(paths);
    for (const label of path_names) {
        const val = filter_path(label, paths).map(e => e[1]);
        const amt = val.reduce((acc, curr) => acc + curr, 0);
        path_totals.push([label, amt]);
    }
    return path_totals;
}
export function get_proposal_id(proposal) {
    return get_object_id(proposal).hex;
}
export function find_program(query, terms) {
    const { action, includes, method, path, params } = query;
    let progs = terms.map(e => parse_program(e));
    if (method !== undefined) {
        progs = progs.filter(e => e.method === method);
    }
    if (action !== undefined) {
        progs = progs.filter(e => regex(action, e.actions));
    }
    if (path !== undefined) {
        progs = progs.filter(e => regex(path, e.paths));
    }
    if (Array.isArray(params)) {
        progs = progs.filter(e => params.every((x, i) => e.params[i] === x));
    }
    if (Array.isArray(includes)) {
        progs = progs.filter(e => includes.every(x => e.params.includes(x)));
    }
    return progs.at(0);
}
export function endorse_proposal(proposal, signer) {
    const msg = get_proposal_id(proposal);
    const pub = signer.pubkey;
    const sig = signer.sign(msg);
    return Buff.join([pub, sig]).hex;
}
