import { createServer } from 'node:http';
import { readFile, readdir, realpath, stat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
import { resolve, join, relative, isAbsolute, dirname, basename, extname } from 'node:path';
import { homedir } from 'node:os';
import { randomUUID, createHash } from 'node:crypto';
import { chromium } from 'playwright-core';

export const VERSION='0.1.1';
const fail=(code,message)=>Object.assign(new Error(message),{code});
function object(value,label){if(!value||typeof value!=='object'||Array.isArray(value))throw fail('INVALID_JOB',`${label}必须是对象。`);}
function keys(value,allowed,label){object(value,label);for(const key of Object.keys(value))if(!allowed.includes(key))throw fail('UNKNOWN_FIELD',`${label}不支持字段:${key}`);}
function inside(root,file){const rel=relative(root,file);return rel===''||(!rel.startsWith('..')&&!isAbsolute(rel));}
async function exists(file){return Boolean(await stat(file).catch(e=>{if(e.code==='ENOENT')return null;throw e;}));}
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');

export async function findBrowser(){
  if(process.env.LSJY_BROWSER_EXECUTABLE){const file=resolve(process.env.LSJY_BROWSER_EXECUTABLE);if(!await exists(file))throw fail('BROWSER_MISSING','LSJY_BROWSER_EXECUTABLE 指定的浏览器不存在。');return file;}
  const roots=[process.env.PLAYWRIGHT_BROWSERS_PATH,join(homedir(),'AppData/Local/ms-playwright'),join(homedir(),'.cache/ms-playwright'),join(homedir(),'Library/Caches/ms-playwright')].filter(Boolean);
  for(const root of roots){
    const folders=(await readdir(root,{withFileTypes:true}).catch(()=>[])).filter(f=>f.isDirectory()&&/^chromium-\d+$/.test(f.name)).sort((a,b)=>b.name.localeCompare(a.name,undefined,{numeric:true}));
    for(const folder of folders)for(const suffix of ['chrome-win64/chrome.exe','chrome-win/chrome.exe','chrome-linux64/chrome','chrome-linux/chrome','chrome-mac/Chromium.app/Contents/MacOS/Chromium']){
      const file=join(root,folder.name,suffix);if(await exists(file))return file;
    }
  }
  throw fail('BROWSER_MISSING','请先安装 Chromium,或用 LSJY_BROWSER_EXECUTABLE 指定已安装的浏览器路径;处理时不会自动联网安装。');
}

export async function serveTool(directory){
  const root=await realpath(directory);
  const server=createServer(async(req,res)=>{
    const headers={'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer'};
    try{
      if(!['GET','HEAD'].includes(req.method)){res.writeHead(405,headers).end();return;}
      if(req.headers.host!==`127.0.0.1:${server.address().port}`){res.writeHead(403,headers).end();return;}
      const pathname=decodeURIComponent(new URL(req.url,'http://127.0.0.1').pathname);
      if(pathname.includes('\0')||pathname.includes('\\')){res.writeHead(400,headers).end();return;}
      const local=resolve(root,'.'+(pathname.endsWith('/')?pathname+'index.html':pathname));
      if(!inside(root,local)){res.writeHead(403,headers).end();return;}
      const canonical=await realpath(local);
      if(!inside(root,canonical)){res.writeHead(403,headers).end();return;}
      const info=await stat(canonical);if(!info.isFile()){res.writeHead(404,headers).end();return;}
      const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.json':'application/json','.svg':'image/svg+xml','.png':'image/png','.woff2':'font/woff2','.wasm':'application/wasm'};
      res.writeHead(200,{...headers,'Content-Type':types[extname(canonical)]||'application/octet-stream','Content-Length':info.size});
      res.end(req.method==='HEAD'?undefined:await readFile(canonical));
    }catch(error){res.writeHead(error.code==='ENOENT'?404:400,headers).end();}
  });
  await new Promise((yes,no)=>{server.once('error',no);server.listen(0,'127.0.0.1',yes);});
  return {origin:`http://127.0.0.1:${server.address().port}`,close:()=>new Promise((yes,no)=>{server.close(error=>error?no(error):yes());server.closeAllConnections();})};
}

async function fields(page){return page.locator('#controls').evaluate(form=>Array.from(form.elements).filter(e=>e.name&&!['submit','button','file','reset'].includes(e.type)).map(e=>({
  name:e.name,type:e.tagName==='SELECT'?'select':e.tagName==='TEXTAREA'?'textarea':e.type,
  label:e.closest('label')?.textContent.trim()||e.getAttribute('aria-label')||e.name,
  default:e.type==='checkbox'?e.checked:e.value,required:e.required,min:e.getAttribute('min'),max:e.getAttribute('max'),step:e.getAttribute('step'),
  options:e.tagName==='SELECT'?Array.from(e.options).map(o=>({value:o.value,label:o.label})):undefined
})));}

async function session(toolDir,fn,timeout=60000){
  const server=await serveTool(toolDir);let browser,deadline,timedOut=false;
  const blocked=[],pageErrors=[];
  try{
    browser=await chromium.launch({headless:true,executablePath:await findBrowser()});
    deadline=setTimeout(()=>{timedOut=true;void browser.close().catch(()=>{});},timeout);
    const context=await browser.newContext({viewport:{width:1280,height:900},acceptDownloads:true,serviceWorkers:'block'});
    await context.route('**/*',route=>{
      const url=new URL(route.request().url());
      if(url.origin===server.origin||['blob:','data:'].includes(url.protocol))return route.continue();
      blocked.push({origin:url.origin,type:route.request().resourceType()});return route.abort();
    });
    const page=await context.newPage();page.setDefaultTimeout(timeout);
    page.on('pageerror',error=>pageErrors.push(error.message));
    await page.goto(server.origin+'/',{waitUntil:'load'});
    await page.locator('#controls').waitFor();
    const result=await fn(page,{blocked,pageErrors,origin:server.origin});
    if(timedOut)throw fail('PROCESS_TIMEOUT','处理超时,本次结果未提交。');
    if(blocked.length)throw fail('EXTERNAL_REQUEST_BLOCKED','工具尝试访问外部网络,已阻止;本次不交付为成功结果。');
    if(pageErrors.length)throw fail('TOOL_SCRIPT_ERROR','工具脚本发生错误:'+pageErrors[0]);
    return result;
  }catch(error){if(timedOut)throw fail('PROCESS_TIMEOUT','处理超时,本次结果未提交。');throw error;}
  finally{clearTimeout(deadline);if(browser)await browser.close();await server.close();}
}

export async function describeTool({tool,toolDir}){
  return session(toolDir,async page=>({schema_version:1,runner_version:VERSION,tool_id:tool.id,name:tool.name,
    max_input_files:tool.count,input_optional:Boolean(tool.optional),input_kind:tool.input||(tool.count?'raster':'parameters'),
    parameters:await fields(page),max_total_input_bytes:60*1024*1024,max_output_bytes:80*1024*1024,
    special:tool.id==='image-crop'?{crop:'原图像素矩形 {x,y,width,height};省略则使用整张图;rotation为顺时针0/90/180/270度'}:tool.id==='gif-maker'?{frames:'文件顺序就是帧序;frame_delays_ms须与文件数量一致,每帧20至5000毫秒'}:null
  }));
}

export function validateJob(job,tool){
  keys(job,['schema_version','tool_id','files','parameters','output_dir','timeout_ms','crop','rotation','frame_delays_ms'],'任务');
  if(job.schema_version!==1||job.tool_id!==tool.id)throw fail('WRONG_TOOL','任务版本或工具ID不匹配。');
  if(!Array.isArray(job.files)||job.files.some(f=>typeof f!=='string'||!isAbsolute(f)))throw fail('INVALID_FILES','files必须是绝对文件路径数组。');
  if(job.files.length>tool.count||(!tool.optional&&tool.count>0&&!job.files.length))throw fail('FILE_COUNT','输入文件数量不符合工具要求。');
  keys(job.parameters??{},Object.keys(job.parameters??{}),'parameters');
  if(typeof job.output_dir!=='string'||!isAbsolute(job.output_dir))throw fail('INVALID_OUTPUT','output_dir必须是新的绝对目录路径。');
  if(job.timeout_ms!==undefined&&(!Number.isInteger(job.timeout_ms)||job.timeout_ms<1000||job.timeout_ms>300000))throw fail('INVALID_TIMEOUT','timeout_ms范围为1000至300000。');
  if((job.crop!==undefined||job.rotation!==undefined)&&tool.id!=='image-crop')throw fail('WRONG_OPTION','只有图片裁剪支持crop/rotation。');
  if(job.crop!==undefined){keys(job.crop,['x','y','width','height'],'crop');for(const k of ['x','y','width','height'])if(!Number.isFinite(job.crop[k])||job.crop[k]<(k==='x'||k==='y'?0:1))throw fail('INVALID_CROP','裁剪坐标和尺寸必须有效。');}
  if(job.rotation!==undefined&&![0,90,180,270].includes(job.rotation))throw fail('INVALID_ROTATION','rotation须为0/90/180/270。');
  if(job.frame_delays_ms!==undefined&&(tool.id!=='gif-maker'||!Array.isArray(job.frame_delays_ms)||job.frame_delays_ms.length!==job.files.length||job.frame_delays_ms.some(n=>!Number.isInteger(n)||n<20||n>5000)))throw fail('INVALID_FRAMES','GIF帧时长数组须对应每个输入,范围20至5000毫秒。');
  return job;
}

async function setParameters(page,parameters,descriptors){
  const entries=Object.entries(parameters).sort(([a],[b])=>Number(descriptors.find(f=>f.name===b)?.type==='checkbox')-Number(descriptors.find(f=>f.name===a)?.type==='checkbox'));
  for(const [name,value] of entries){
    const spec=descriptors.find(f=>f.name===name);if(!spec)throw fail('UNKNOWN_PARAMETER',`未知参数:${name}`);
    if(['number','range'].includes(spec.type)){
      if(typeof value!=='number'||!Number.isFinite(value))throw fail('INVALID_PARAMETER',`${name}必须为有限数值。`);
      if(spec.min!==null&&value<Number(spec.min)||spec.max!==null&&value>Number(spec.max))throw fail('INVALID_PARAMETER',`${name}超出范围。`);
    }else if(spec.type==='checkbox'){
      if(typeof value!=='boolean')throw fail('INVALID_PARAMETER',`${name}必须为布尔值。`);
    }else if(typeof value!=='string')throw fail('INVALID_PARAMETER',`${name}必须为字符串。`);
    if(spec.type==='select'&&!spec.options.some(o=>o.value===value))throw fail('INVALID_PARAMETER',`${name}不是有效选项。`);
    if(spec.type==='color'&&!/^#[0-9a-fA-F]{6}$/.test(value))throw fail('INVALID_PARAMETER',`${name}必须为六位HEX颜色。`);
    await page.locator('#controls').evaluate((form,{name,value})=>{
      const e=form.elements.namedItem(name);if(e.type==='checkbox')e.checked=value;else e.value=String(value);
      e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}));
    },{name,value});
  }
  const invalid=await page.locator('#controls').evaluate(form=>Array.from(form.elements).filter(e=>e.willValidate&&!e.validity.valid).map(e=>e.name));
  if(invalid.length)throw fail('INVALID_PARAMETER','参数未通过工具校验:'+invalid.join(', '));
}

async function specialOptions(page,job){
  if(job.tool_id==='gif-maker'&&job.frame_delays_ms){
    for(const [i,delay] of job.frame_delays_ms.entries()){
      await page.locator(`[data-delay="${i}"]`).fill(String(delay));
      await page.locator(`[data-delay="${i}"]`).dispatchEvent('change');
    }
  }
  if(job.tool_id==='image-crop'){
    await page.locator('cropper-image').evaluate(async image=>{await image.$ready();});
    const result=await page.evaluate(async({crop,rotation})=>{
      const image=document.querySelector('cropper-image'),canvas=document.querySelector('cropper-canvas'),selection=document.querySelector('cropper-selection');
      const original=await image.$ready();const w=original.naturalWidth,h=original.naturalHeight;
      const box=crop||{x:0,y:0,width:w,height:h};
      if(box.x+box.width>w||box.y+box.height>h)return {error:'裁剪矩形超出原图。'};
      const rotated=rotation===90||rotation===270;
      const fit=Math.min(canvas.clientWidth/(rotated?h:w),canvas.clientHeight/(rotated?w:h));
      const scale=2**Math.floor(Math.log2(fit));
      const angle=rotation*Math.PI/180,a=Math.cos(angle)*scale,b=Math.sin(angle)*scale,c=-b,d=a;
      image.$setTransform(a,b,c,d,(canvas.clientWidth-w)/2,(canvas.clientHeight-h)/2);
      const pts=[[box.x,box.y],[box.x+box.width,box.y],[box.x,box.y+box.height],[box.x+box.width,box.y+box.height]].map(([x,y])=>[canvas.clientWidth/2+a*(x-w/2)+c*(y-h/2),canvas.clientHeight/2+b*(x-w/2)+d*(y-h/2)]);
      const xs=pts.map(p=>p[0]),ys=pts.map(p=>p[1]);
      const x=Math.min(...xs),y=Math.min(...ys),cw=Math.max(...xs)-x,ch=Math.max(...ys)-y;
      selection.precise=true;selection.aspectRatio=NaN;selection.$change(x,y,cw,ch,NaN,true);
      return {crop:box,rotation,source_width:w,source_height:h};
    },{crop:job.crop,rotation:job.rotation||0});
    if(result.error)throw fail('INVALID_CROP',result.error);
    return result;
  }
}

export function safeDownloadName(name,index){
  if(typeof name!=='string'||!name||name==='.'||name==='..'||/[<>:"/\\|?*\x00-\x1f]/.test(name)||/[. ]$/.test(name)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name))throw fail('INVALID_RESULT_NAME','工具返回了不安全的文件名。');
  return `${String(index+1).padStart(3,'0')}-${name}`;
}

export async function runJob({tool,toolDir,job}){
  validateJob(job,tool);
  const output=resolve(job.output_dir);
  if(await exists(output))throw fail('OUTPUT_EXISTS','输出目录已存在,请选用新的目录,避免覆盖已有资料。');
  let inputBytes=0;const inputs=[];
  for(const file of job.files){
    const info=await stat(file);if(!info.isFile())throw fail('INVALID_FILES','输入必须是普通文件。');
    const cap=tool.input==='svg'?1024*1024:20*1024*1024;
    if(info.size>cap)throw fail('INPUT_TOO_LARGE','单文件超过该工具的大小限制。');
    inputBytes+=info.size;inputs.push({name:basename(file),bytes:info.size,sha256:sha(await readFile(file))});
  }
  if(inputBytes>60*1024*1024)throw fail('INPUT_TOO_LARGE','总输入超过60MB。');
  await mkdir(dirname(output),{recursive:true});
  const staging=await mkdtemp(join(dirname(output),'.lsjy-'+randomUUID()+'-'));
  let committed=false;
  try{
    const result=await session(toolDir,async(page,signals)=>{
      if(job.files.length){
        await page.locator('#file-input').setInputFiles(job.files);
        await page.waitForFunction(()=>{const form=document.querySelector('#controls');return !form.inert&&form.getAttribute('aria-busy')!=='true';});
        if(await page.locator('#status').getAttribute('class')==='error')throw fail('INPUT_REJECTED',await page.locator('#status').innerText());
        const actual=await page.locator('#files .file-row').count();if(actual!==job.files.length)throw fail('INPUT_REJECTED','工具未完整接收所有文件。');
      }
      await setParameters(page,job.parameters||{},await fields(page));
      const special=await specialOptions(page,job);
      const effective=Object.fromEntries((await fields(page)).map(f=>[f.name,['number','range'].includes(f.type)?Number(f.default):f.default]));
      await page.locator('#process').click();
      await page.waitForFunction(()=>{const form=document.querySelector('#controls'),status=document.querySelector('#status');return !form.inert&&form.getAttribute('aria-busy')!=='true'&&(status.classList.contains('error')||status.textContent==='处理完成');});
      if(await page.locator('#status').getAttribute('class')==='error')throw fail('TOOL_REJECTED',await page.locator('#status').innerText());
      const count=await page.locator('[data-download]').count();if(count<1||count>110)throw fail('INVALID_RESULTS','结果数量无效。');
      const artifacts=[];let total=0;
      for(let index=0;index<count;index++){
        const waiting=page.waitForEvent('download');await page.locator('[data-download]').nth(index).click();const download=await waiting;
        const name=safeDownloadName(download.suggestedFilename(),index),dest=join(staging,name);
        await download.saveAs(dest);const error=await download.failure();if(error)throw fail('DOWNLOAD_FAILED','结果保存失败。');
        const bytes=await readFile(dest);total+=bytes.length;
        if(!bytes.length||total>80*1024*1024)throw fail('INVALID_RESULTS','结果为空或总量超过80MB。');
        artifacts.push({path:name,original_name:download.suggestedFilename(),bytes:bytes.length,sha256:sha(bytes),extension:extname(name)});
      }
      return {schema_version:1,status:'completed',tool_id:tool.id,runner_version:VERSION,tool_version:tool.release_version||'local-build',tool_resources_sha256:tool.resources_sha256||null,completed_at:new Date().toISOString(),
        parameters:job.parameters||{},effective_parameters:effective,special,inputs,files:artifacts,network:{external_requests:signals.blocked.length,processing:'local'}};
    },job.timeout_ms||60000);
    await writeFile(join(staging,'result.json'),JSON.stringify(result,null,2)+'\n',{flag:'wx'});
    if(await exists(output))throw fail('OUTPUT_EXISTS','输出目录在运行期间被创建,拒绝覆盖。');
    await rename(staging,output);committed=true;return result;
  }finally{
    if(!committed){
      if(dirname(staging)!==dirname(output)||!basename(staging).startsWith('.lsjy-'))throw fail('UNSAFE_CLEANUP','临时目录不符合清理边界。');
      await rm(staging,{recursive:true,force:true});
    }
  }
}