import{commands,config,hooks,http,lifecycle,log}from"motrix:plugin-api";var FILE_PAGE_RE=/^https?:\/\/commons\.wikimedia\.org\/wiki\/(File:[^?#]+)/i,API_UA="MotrixURLResolver/1.0 (+https://motrix.app)";function match(url){return FILE_PAGE_RE.test(url)}async function resolve(url,deps){let m=FILE_PAGE_RE.exec(url);if(!m?.[1])return null;let title;try{title=decodeURIComponent(m[1])}catch{title=m[1]}let api=`https://commons.wikimedia.org/w/api.php?action=query&format=json&prop=imageinfo&iiprop=url&titles=${encodeURIComponent(title)}`,resp;try{resp=await deps.http(api,{headers:{"User-Agent":API_UA},timeoutMs:1e4})}catch(e){return deps.log.warn("commons: api request failed",{err:String(e)}),null}if(resp.status!==200)return deps.log.warn("commons: api non-200",{status:resp.status}),null;let data;try{data=JSON.parse(resp.body)}catch{return deps.log.warn("commons: response not valid JSON"),null}let pages=data.query?.pages;if(!pages)return deps.log.info("commons: no pages in response",{title}),null;let directUrl=Object.values(pages)[0]?.imageinfo?.[0]?.url;return typeof directUrl!="string"||directUrl.length===0?(deps.log.info("commons: no imageinfo url",{title}),null):{kind:"direct",directUrl}}function match2(_url){return!0}async function resolve2(_url,_deps){return null}var SITE_RESOLVERS=[{name:"commons",match,resolve},{name:"generic",match:match2,resolve:resolve2}];async function resolveUrl(url,deps){for(let r of SITE_RESOLVERS)if(r.match(url))return deps.log.debug("site resolver matched",{resolver:r.name,url}),r.resolve(url,deps);return null}var DEFAULT_QUALITY="720p";function buildDeps(quality){return{quality,http:async(url,init)=>{let r=await http.request({method:init?.method??"GET",url,headers:init?.headers?Object.entries(init.headers).map(([name,value])=>({name,value})):void 0,body:init?.jsonBody!==void 0?{type:"json",data:init.jsonBody}:void 0,responseType:"text",timeoutMs:init?.timeoutMs??1e4});return{status:r.status,body:r.body}},log}}async function readQuality(){let v=await config.get("preferredQuality");return v==="1080p"||v==="720p"||v==="480p"?v:DEFAULT_QUALITY}hooks.beforeCreate(async ctx=>{if(ctx.type!=="http")return ctx;let url=ctx.uris[0];if(!url)return ctx;let quality=await readQuality();try{let r=await resolveUrl(url,buildDeps(quality));if(r&&r.kind==="direct"){let headerArr=Object.entries(r.headers??{}).map(([name,value])=>({name,value}));ctx.update({uris:[r.directUrl],headers:headerArr})}}catch(e){log.warn("resolver failed",{err:String(e)})}return ctx});commands.register("motrix.url-resolver.resolve",async raw=>{let args=raw,quality=args.quality??DEFAULT_QUALITY,r=await resolveUrl(args.url,buildDeps(quality));if(!r)throw new Error("no resolver matched");return r});commands.register("motrix.url-resolver.flushCache",async()=>{log.debug("flushCache invoked (no-op)")});lifecycle.onDeactivate(async()=>{log.info("shutting down url-resolver")});
