/**
 * 光湖原生数据库 · 铸渊大脑服务器 BS-SG-001
 * HLDP-ZY://native-db/v0.1 · D118
 */
const http=require('http');const fs=require('fs');const path=require('path');
const {execSync}=require('child_process');const git=require('isomorphic-git');

const NATIVE_DIR='/data/guanghulab/native-repo';
const GIT_DIR=path.join(NATIVE_DIR,'.git');
const PORT=3912;

async function ensureRepo(){if(!fs.existsSync(GIT_DIR))await git.init({fs,dir:GIT_DIR,bare:true,defaultBranch:'main'})}

async function hldpWrite(i){const fp=path.join(NATIVE_DIR,i.path);const dir=path.dirname(fp);if(!fs.existsSync(dir))fs.mkdirSync(dir,{recursive:true});fs.writeFileSync(fp,i.content,'utf8');await git.add({fs,dir:NATIVE_DIR,filepath:i.path});const sha=await git.commit({fs,dir:NATIVE_DIR,message:JSON.stringify({hldp_v:'3.0',intent:i.intent||'grow_leaf',path:i.path,epoch:i.epoch||'D118',ts:new Date().toISOString()}),author:{name:'ICE-GL-ZY001',email:'zhuyuan@guanghulab.com'}});return{ok:true,sha,path:i.path}}

function hldpRead(i){const fp=path.join(NATIVE_DIR,i.path);if(!fs.existsSync(fp))return{ok:false,error:'NOT_FOUND'};return{ok:true,path:i.path,content:fs.readFileSync(fp,'utf8'),size:fs.statSync(fp).size}}

function hldpTree(i){const dp=path.join(NATIVE_DIR,i.path||'');if(!fs.existsSync(dp))return{ok:false,error:'NOT_FOUND'};const e=fs.readdirSync(dp,{withFileTypes:true}).filter(x=>!x.name.startsWith('.')&&x.name!=='node_modules').map(x=>({name:x.name,type:x.isDirectory()?'dir':'file',path:path.join(i.path||'',x.name)}));return{ok:true,path:i.path,count:e.length,entries:e.slice(0,20)}}

function hldpSearch(i){try{const q=i.query.replace(/[$\\`"!]/g,'');const r=execSync('/usr/bin/rg -n --no-heading -M 200 "'+q+'" '+NATIVE_DIR+' --glob "!.git" --glob "!node_modules" 2>/dev/null',{encoding:'utf8',timeout:10000});if(!r.trim())return{ok:true,query:i.query,count:0,results:[]};const results=r.trim().split('\n').slice(0,30).map(l=>{const[f,ln,...rt]=l.split(':');return{file:f.replace(NATIVE_DIR+'/',''),line:parseInt(ln),content:rt.join(':').trim()}});return{ok:true,query:i.query,count:results.length,results}}catch(e){if(e.status===1)return{ok:true,query:i.query,count:0,results:[]};return{ok:false,error:e.message}}}

async function startServer(){await ensureRepo();http.createServer(async(req,res)=>{res.setHeader('Content-Type','application/json;charset=utf-8');res.setHeader('X-HLDP-Version','3.0');res.setHeader('X-Guardian','ICE-GL-ZY001');res.setHeader('Access-Control-Allow-Origin','*');if(req.method==='OPTIONS'){res.writeHead(204);return res.end()}if(req.method!=='POST'){res.writeHead(405);return res.end(JSON.stringify({error:'POST only'}))}let body='';req.on('data',c=>body+=c);req.on('end',async()=>{try{const i=JSON.parse(body);let r;if(req.url==='/hldp/write')r=await hldpWrite(i);else if(req.url==='/hldp/read')r=hldpRead(i);else if(req.url==='/hldp/tree')r=hldpTree(i);else if(req.url==='/hldp/search')r=hldpSearch(i);else if(req.url==='/hldp/health')r={ok:true,service:'guanghu-native-db',version:'0.1.0',server:'BS-SG-001',uptime:process.uptime()};else{res.writeHead(404);return res.end(JSON.stringify({error:'unknown'}))}res.writeHead(200);res.end(JSON.stringify(r))}catch(e){res.writeHead(500);res.end(JSON.stringify({ok:false,error:e.message}))}})}).listen(PORT,'127.0.0.1',()=>console.log('NATIVE-DB:3912'))}

startServer().catch(e=>console.error(e));
