#!/usr/bin/env node
/** create_project.js — 生成结构草稿。注意：它只搭骨架+空镜头，
 *  真正的镜头设计必须按 SKILL.md Step 0 手动完成。 */
const fs=require("fs"),path=require("path");
const arg=(n,d)=>{const i=process.argv.indexOf("--"+n);return i>=0?process.argv[i+1]:d};
const flag=n=>process.argv.includes("--"+n);
const title=arg("title","未命名"),audio=arg("audio",""),srtP=arg("srt",""),
      out=arg("out","output/video.html"),bgm=arg("bgm",""),noBgm=flag("no-bgm");
if(!audio||!srtP){console.error("需 --audio 和 --srt");process.exit(1);}
const toSec=ts=>{const[h,m,r]=ts.split(":");const[s,ms]=r.split(",");return +h*3600+ +m*60+ +s+ +ms/1000};
const subs=fs.readFileSync(srtP,"utf8").replace(/\r/g,"").trim().split(/\n\n+/).map(b=>{
  const L=b.split("\n"),tl=L.find(l=>l.includes("-->"));if(!tl)return null;
  const[a,bb]=tl.split("-->").map(s=>s.trim());
  let zh=(L[L.indexOf(tl)+1]||""); const hl=[]; zh=zh.replace(/\*(.+?)\*/g,(_,w)=>{hl.push(w);return w});
  return{start:toSec(a),end:toSec(bb),text:zh,hl}}).filter(Boolean);
const kw=[...new Set(subs.flatMap(s=>s.hl))];
// 草稿：每句一个 bigText 空镜头，等待人工按 Step 0 替换
const cues=subs.map(s=>({d:+(s.end-s.start).toFixed(2),f:"bigText",cut:"red",t:s.text.replace(/\*/g,""),s:""}));
let h=fs.readFileSync(path.join(__dirname,"../assets/template.html"),"utf8");
const bgmTag=(!noBgm&&bgm)?`<audio id="bgm" src="${bgm}" preload="auto" loop></audio>`:"";
h=h.replace(/\{\{TITLE\}\}/g,title).replace(/\{\{HUD_LABEL\}\}/g,"DRAFT").replace(/\{\{START_TITLE\}\}/g,title)
   .replace(/\{\{AUDIO_SRC\}\}/g,audio).replace(/\{\{BGM_TAG\}\}/g,bgmTag)
   .replace(/\{\{CUES_JSON\}\}/g,JSON.stringify(cues))
   .replace(/\{\{SUBS_JSON\}\}/g,JSON.stringify(subs.map(s=>({start:s.start,end:s.end,text:s.text.replace(/\*/g,"")}))))
   .replace(/\{\{KEYWORDS_JSON\}\}/g,JSON.stringify(kw));
fs.mkdirSync(path.dirname(out),{recursive:true});fs.writeFileSync(out,h,"utf8");
console.log(`✓ 草稿已生成 ${out} (${cues.length}句)`);
console.log("⚠ 这只是结构草稿，每句都是占位大字。请按 SKILL.md Step 0 为每句设计贴合内容的镜头。");
