import{ok,err}from"./_deps/shared/index.js";import{splitXorIDA,reconstructXorIDA,nextOddPrime,pkcs7Pad,pkcs7Unpad,generateHMAC,verifyHMAC,toBase64,fromBase64,generateUUID,formatShareHeader,parseShareHeader}from"./crypto-utils.js";export const DEFAULT_SPLIT_CONFIG={totalShares:3,threshold:2};export async function splitForChannel(r,e=DEFAULT_SPLIT_CONFIG){const{totalShares:t,threshold:n}=e;if(t<2||n<2||n>t)return err("SPLIT_FAILED:INVALID_PARAMS");return splitForChannelWithGroupId(r,e,generateUUID())}export async function splitForChannelWithGroupId(r,e,t){const{totalShares:n,threshold:a}=e;if(n<2||a<2||a>n)return err("SPLIT_FAILED:INVALID_PARAMS");let o,s,I;try{const e=nextOddPrime(n),t=pkcs7Pad(r,e-1),c=await generateHMAC(t);s=c.key,I=c.signature,o=splitXorIDA(t,n,a)}catch{return err("SPLIT_FAILED:CRYPTO_NOT_LOADED")}const c=toBase64(s),A=toBase64(I),i=o.map((r,e)=>({data:formatShareHeader(toBase64(r)),index:e,total:n,threshold:a,groupId:t,hmacKey:c,hmacSig:A}));return ok(i)}export async function reconstructFromChannel(r){const e=validateShares(r);if(!e.ok)return e;const{k:t,n:n}=e.value;return reconstructValidated(r.slice(0,t),n,t)}function validateShares(r){if(0===r.length)return err("INSUFFICIENT_SHARES");const e=r[0],t=e.threshold,n=e.total;if(r.length<t)return err("INSUFFICIENT_SHARES");const a=new Set;for(const o of r){if(o.groupId!==e.groupId)return err("INCONSISTENT_SHARES");if(o.total!==n||o.threshold!==t)return err("INCONSISTENT_SHARES");if(o.index<0||o.index>=n)return err("INVALID_SHARE_DATA");if(a.has(o.index))return err("INVALID_SHARE_DATA");a.add(o.index)}return ok({k:t,n:n,groupId:e.groupId})}async function reconstructValidated(r,e,t){let n;try{n=r.map(r=>fromBase64(parseShareHeader(r.data)))}catch{return err("INVALID_SHARE_DATA:BASE64")}const a=r.map(r=>r.index),o=r[0];let s,I;try{s=fromBase64(o.hmacKey),I=fromBase64(o.hmacSig)}catch{return err("INVALID_SHARE_DATA:HMAC_DECODE")}try{const r=reconstructXorIDA(n,a,e,t);if(!await verifyHMAC(s,r,I))return err("HMAC_VERIFICATION_FAILED");const o=nextOddPrime(e),c=pkcs7Unpad(r,o-1);return c.ok?ok(c.value):err("UNPAD_FAILED")}catch{return err("SPLIT_FAILED:CRYPTO_NOT_LOADED")}}