import {readFile,stat} from 'node:fs/promises';
import {dirname,resolve,join,relative,isAbsolute} from 'node:path';
import {fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';
import {describeTool,runJob} from './runner.mjs';
const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');
try{
const args=process.argv.slice(2);
if(!((args.length===1&&args[0]==='--describe')||(args.length===2&&args[0]==='--job')))throw new Error('使用 --describe 或 --job <任务JSON路径>。');
const manifest=JSON.parse(await readFile(join(root,'manifest.json'),'utf8'));
for(const item of manifest.files){
const file=resolve(root,item.path),rel=relative(root,file);if(rel.startsWith('..')||isAbsolute(rel))throw new Error('制品路径越界。');
const bytes=await readFile(file);if(bytes.length!==item.bytes||createHash('sha256').update(bytes).digest('hex')!==item.sha256)throw new Error('制品文件改变,请重新构建或取得完整版本:'+item.path);
}
const config=JSON.parse(await readFile(join(root,'tool.json'),'utf8'));const toolDir=join(root,'assets/tool');
const result=args[0]==='--describe'?await describeTool({tool:config.tool,toolDir}):await runJob({tool:config.tool,toolDir,job:JSON.parse(await readFile(resolve(args[1]),'utf8'))});
console.log(JSON.stringify(result,null,2));
}catch(error){console.error(JSON.stringify({status:'failed',code:error.code||'SKILL_ERROR',message:error.message}));process.exitCode=1;}