"use strict";var I=require("axios"),h=require("lodash.omitby"),y=require("lodash.isundefined"),f=require("fs"),j=require("path"),p=(e=>(e.small="s",e.medium="m",e.large="l",e))(p||{});class b extends Error{statusCode;constructor(r,t){super(r),this.statusCode=t,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}var w=(e=>(e.search="/search",e.me="/me",e))(w||{});const g="https://api.trace.moe";function L(e){const r=I.create({baseURL:g,headers:{"Content-Type":"application/x-www-form-urlencoded"}});return r.interceptors.request.use(t=>(e&&(t.headers["x-trace-key"]=e),t)),r.interceptors.response.use(t=>t,t=>{throw t.response?.data?.error?new b(t.response.data.error,t.response.status):t.response?.status==429?t:new Error(t.message)}),r}function v(e,r){return new Promise(async(t,a)=>{async function o(){try{const s=await e();t(s.data)}catch(s){if(!(s instanceof I.AxiosError)){a(s);return}if(!r||s.response?.status!==429){a(new Error(s.message));return}setTimeout(async()=>{o()},s.response.headers["x-ratelimit-reset"]*1e3-Date.now())}}o()})}function S(e,r){if(Object.values(e).length===0&&!r)return"";const t={url:r,cutBorders:e.shouldCutBlackBorders?null:void 0,anilistID:e.anilistID!==void 0?String(e.anilistID):void 0,anilistInfo:e.shouldIncludeExtraAnilistInfo?null:void 0};return Object.entries(t).filter(([a,o])=>o!==void 0).reduce((a,[o,s],m)=>a+(m>0?"&":"")+o+(s!==null?"="+s:""),"?")}function A(e){const r=e.result.map(M);return{checkedFramesCount:e.frameCount,results:r}}function M(e){const r=e.anilist.title?{nativeTitle:e.anilist.title?.native??void 0,romajiTitle:e.anilist.title?.romaji,englishTitle:e.anilist.title?.english??void 0}:void 0,t={id:typeof e.anilist=="number"?e.anilist:e.anilist.id,malID:e.anilist.idMal,title:r?h(r,y):void 0,synonyms:e.anilist.synonyms,isNSFWAnime:e.anilist.isAdult},a={anilistInfo:h(t,y),filename:e.filename,episode:e.episode??void 0,fromTimestamp:e.from,toTimestamp:e.to,similarityPercentage:E(e.similarity*100,3),videoURL:e.video,imageURL:e.image};return h(a,y)}function P(e,r,t){const a=[".mp4"],o=[".jpg",".jpeg"];if(t){const s=t.substring(t.lastIndexOf(".")).toLowerCase();r&&!a.includes(s)?t+=a[0]:!r&&!o.includes(s)&&(t+=o[0])}else{const s=e.filename.substring(0,e.filename.lastIndexOf(".")),m=r?a[0]:o[0];t=`${s}@${new URL(e.imageURL).searchParams.get("t")}${m}`}return t}function E(e,r){const t=Math.pow(10,r);return Math.round((e+Number.EPSILON)*t)/t}const F=g+w.search,z=g+w.me;function U(e){const r=L(e?.apiKey),t=e?.shouldRetry;async function a(n,i){n instanceof URL&&(n=n.href);const u=F+S({...i},n),c=()=>r.get(u),l=await v(c,t);return Object.freeze(A(l))}async function o(n,i){const u=F+S({...i}),c=await f.promises.readFile(n),l=()=>r.post(u,c),d=await v(l,t);return Object.freeze(A(d))}async function s(){const n=()=>r.get(z),i=await v(n,t);return Object.freeze({id:i.id,priority:i.priority,concurrency:i.concurrency,totalQuota:i.quota,remainingQuota:i.quota-i.quotaUsed})}async function m(n,i){const u=i?.size??p.medium,c=`${n.videoURL}&size=${u}${i?.shouldMute?"&mute":""}`;return R(c,n,!0,i?.directory,i?.name)}async function O(n,i){const u=i?.size??p.medium,c=`${n.imageURL}&size=${u}`;return R(c,n,!1,i?.directory,i?.name)}async function R(n,i,u,c=".",l){f.existsSync(c)||await f.promises.mkdir(c,{recursive:!0}),l=P(i,u,l);const d=j.join(c,l),T=Buffer.from((await r.get(n,{responseType:"arraybuffer"})).data);return await f.promises.writeFile(d,T),d}return Object.freeze({apiKey:e?.apiKey??null,searchForAnimeSceneWithMediaURL:a,searchForAnimeSceneWithMediaAtPath:o,fetchAPILimits:s,downloadVideoFromResult:m,downloadImageFromResult:O})}exports.MediaSize=p,exports.SearchError=b,exports.createTraceMoeAPIWrapper=U;