import 'server-only';
import fs from 'node:fs';
import {deviceUiFile} from './app-ui-files';

/**
 * The original app captures are immutable. This adapter only reads an app's
 * own embedded settings specification, then saves edited fictional values to
 * the owning Larpdevice project (never to the original site).
 */
export type NativeField={key:string;label:string;type:string;value:unknown;options?:Array<{value:string;label:string}>};
export type NativeSpec={title:string;url:string;fields:NativeField[]};
const SUPPORTED=new Set(['text','textarea','number','money','select','toggle','image','list','date','time','color']);
type Assignment={start:number;end:number;value:Record<string,unknown>};
/** Read a JSON object assigned to a window variable, even when the same
 * <script> contains the app's long-press editor implementation afterwards. */
function assignedObject(html:string,name:string):Assignment|null{
 const marker='window.'+name+'=';const start=html.indexOf(marker);
 if(start<0)return null;
 let i=start+marker.length,depth=0,inString=false,escaped=false;
 if(html[i]!=='{')return null;
 const contentStart=i;
 for(;i<html.length;i++){
  const char=html[i];
  if(inString){if(escaped){escaped=false;continue}if(char==='\\'){escaped=true;continue}if(char==='"')inString=false;continue}
  if(char==='"'){inString=true;continue}
  if(char==='{')depth++;if(char==='}'){depth--;if(depth===0){try{const value=JSON.parse(html.slice(contentStart,i+1));return value&&typeof value==='object'&&!Array.isArray(value)?{start,end:i+1,value}:null}catch{return null}}}
  if(i-contentStart>4_000_000)return null;
 }
 return null;
}

function safeObject(v:unknown):v is Record<string,unknown>{return !!v&&typeof v==='object'&&!Array.isArray(v)}
export function nativeSpecFromHtml(html:string):NativeSpec|null{
 const found=assignedObject(html,'__LKE');if(!found)return null;
 try{
  const raw=found.value as {title?:unknown;url?:unknown;sections?:Array<{fields?:Array<Record<string,unknown>>}>};
  const fields:NativeField[]=[];const seen=new Set<string>();
  for(const section of raw.sections||[])for(const f of section.fields||[]){
   const key=f.k;const type=String(f.type||'text');
   if(typeof key!=='string'||!/^\w[\w-]{0,64}$/.test(key)||seen.has(key)||!SUPPORTED.has(type))continue;
   seen.add(key);
   const options:Array<{value:string;label:string}>=[];
   for(const option of Array.isArray(f.options)?f.options:[]){
    if(typeof option==='string')options.push({value:option,label:option});
    else if(Array.isArray(option))options.push({value:String(option[0]??''),label:String(option[1]??option[0]??'')});
    else if(safeObject(option))options.push({value:String(option.value??option.v??''),label:String(option.label??option.name??option.value??'')});
   }
   fields.push({key,label:String(f.label||f.name||key).slice(0,100),type,value:f.value??null,...(options.length?{options}:{})});
  }
  return fields.length?{title:String(raw.title||'App settings').slice(0,100),url:String(raw.url||''),fields}:null;
 }catch{return null}
}
export function getNativeSpec(slug:string,device:'phone'|'desktop'='phone'):NativeSpec|null{
 const source=deviceUiFile(slug,device);
 if(!source)return null;
 return nativeSpecFromHtml(fs.readFileSync(source,'utf8'));
}
/** The original mobile and desktop built-in panels can expose different fields.
 * Preserve both sets while validating any saved key against a real panel.
 * The original HTML, the popup's title and its "on in" classes remain unchanged. */
export function getCombinedNativeSpec(slug:string):NativeSpec|null{
 const phone=getNativeSpec(slug,'phone');const desktop=getNativeSpec(slug,'desktop');
 if(!phone)return desktop;if(!desktop)return phone;
 const fields=[...phone.fields];const seen=new Set(fields.map(f=>f.key));
 for(const field of desktop.fields)if(!seen.has(field.key)){fields.push(field);seen.add(field.key)}
 return {title:phone.title||desktop.title,url:phone.url||desktop.url,fields};
}
/** Compare each user-supplied key to the actual shipped editor definition. */
export function validateNativePatch(spec:NativeSpec,patch:unknown):{valid:true;changes:Record<string,unknown>}|{valid:false;error:string}{
 if(!safeObject(patch)||Object.keys(patch).length===0||Object.keys(patch).length>100)return {valid:false,error:'No valid settings selected.'};
 const fields=new Map(spec.fields.map(f=>[f.key,f]));const changes:Record<string,unknown>={};
 for(const [key,value] of Object.entries(patch)){
  const field=fields.get(key);if(!field)return {valid:false,error:`Unknown app setting: ${key}`};
  const type=field.type;
  if(type==='image'){
   if(typeof value!=='string'||value.length>260000||!(value===''||/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(value)))return {valid:false,error:`${field.label}: choose a small PNG, JPEG, or WebP picture.`};
  }else if(type==='toggle'){
   if(typeof value!=='boolean')return {valid:false,error:`${field.label}: expected a yes/no value.`};
  }else if(type==='money'||type==='number'){
   if(typeof value!=='number'||!Number.isFinite(value)||Math.abs(value)>1e12)return {valid:false,error:`${field.label}: use a valid number.`};
  }else if(type==='list'){
   if(!Array.isArray(value)||JSON.stringify(value).length>120000)return {valid:false,error:`${field.label}: invalid or oversized list.`};
  }else{
   if(typeof value!=='string'||value.length>2000||/[\u0000-\u0008\u000b\u000e-\u001f]/.test(value))return {valid:false,error:`${field.label}: invalid text.`};
   if(type==='select'&&field.options?.length&&!field.options.some(x=>x.value===value))return {valid:false,error:`${field.label}: choose a listed option.`};
  }
  changes[key]=value;
 }
 if(JSON.stringify(changes).length>300000)return {valid:false,error:'Settings are too large.'};
 return {valid:true,changes};
}

function equals(a:unknown,b:unknown){return JSON.stringify(a)===JSON.stringify(b)}
function keyNorm(value:string){return value.toLowerCase().replace(/[^a-z0-9]/g,'')}
const aliases:Record<string,string[]>={
 firstName:['first','name'],lastName:['last'],holderFirst:['first'],holderLast:['last'],
 avatar:['pic','photo','avatar','image'],avatarUrl:['avatar','pic','photo','image','logo'],photo:['avatar','pic'],shopLogo:['logo','avatar'],bizLogo:['logo','avatar'],
 first:['firstName'],holder:['name','holder'],displayName:['name','displayName','persona'],
 businessName:['name','businessName'],storeName:['name','storeName'],shopName:['name','shopName'],
 channelName:['name','channelName'],meName:['name'],teamName:['teamName'],developerName:['developerName'],
 bankLast4:['last4','bankLast4'],last4:['last4'],bankName:['bankName','bank'],
 balance:['balance','cash'],cashUsd:['cash','balance'],cashBalanceUsd:['cash','balance'],
 currency:['currency','code'],handle:['handle','tag','cashtag'],username:['username','userName','user'],
 appearance:['appearance','theme'],theme:['theme','appearance'],rewardsLevel:['level'],rewardsPoints:['points'],
 liveTicks:['ticks'],accountName:['accountName','name'],cashUsdcUsd:['usdc'],
 };
function applyBootValues(boot:unknown,spec:NativeSpec,changes:Record<string,unknown>):number{
 if(!safeObject(boot))return 0;
 let changed=0;
 const seen=new Set<object>();
 // Prefer exact field/key matches. Only use value-only matching for distinctive,
 // nonempty primitives so editing one zero or common currency code cannot corrupt data.
 const entries=Object.entries(changes).map(([key,value])=>({key,value,original:spec.fields.find(f=>f.key===key)?.value}));
 function walk(node:unknown,depth=0){if(!node||typeof node!=='object'||seen.has(node)||depth>24)return;
  seen.add(node);
  if(Array.isArray(node)){for(const value of node)walk(value,depth+1);return}
  for(const [key,value] of Object.entries(node as Record<string,unknown>)){
   if(['id','owner','path','url','base','assets','now','today','tz'].includes(key))continue;
   for(const item of entries){
    const direct=[item.key,...(aliases[item.key]||[])].some(k=>keyNorm(k)===keyNorm(key));
    const original=item.original;
    const primitive=typeof value==='string'||typeof value==='number';
    const distinctive=typeof original==='string'?original.trim().length>=5&&!['USD','CAD','GBP','EUR','USDT'].includes(original):typeof original==='number'?Math.abs(original)>10:false;
    const oldMatches=equals(value,original)||(typeof value==='number'&&typeof original==='string'&&Number(original)===value);
    if(direct&&oldMatches||(!direct&&primitive&&distinctive&&oldMatches)){
      (node as Record<string,unknown>)[key]=item.value;changed++;break;
    }
   }
   walk((node as Record<string,unknown>)[key],depth+1);
  }
 }
 walk(boot);
 return changed;
}

/** Pre-rendered captured text can otherwise show stale values before the
 * source app hydrates. Update matching display-only text, including rerenders,
 * without altering the original markup structure or application click targets. */
const visualScript=String.raw`(function(){
'use strict';var el=document.getElementById('ld-native-visual-config');if(!el)return;
var changes=[];try{changes=JSON.parse(el.textContent||'[]')}catch(e){return}
var pending=false,updating=false;
function amountText(value){return Number(value).toLocaleString('en-US',{maximumFractionDigits:2,minimumFractionDigits:2})}
function displayMatch(text,old){
 if(typeof old==='string'&&old.length>=3)return text===old;
 if(typeof old==='number'&&Math.abs(old)>=10){var clean=text.replace(/[$£€¥,\s]/g,'');return clean!==''&&/^[-+]?[0-9]+(?:\.[0-9]+)?$/.test(clean)&&Number(clean)===old}
 return false
}
function replaceText(node){if(!node||!node.nodeValue||!node.parentElement)return;
 if(node.parentElement.closest('#lke,#ld-inline-ui,#larpdevice-simulation-notice,[aria-label*="SIMULATION"],input,textarea,select'))return;
 var raw=node.nodeValue,trim=raw.trim();if(!trim||trim.length>160)return;
 for(var i=0;i<changes.length;i++){
  var item=changes[i];if(item.type==='image')continue;
  if(displayMatch(trim,item.before)){
   var value=String(item.after);
   if(typeof item.before==='number'&&typeof item.after==='number'){
    value=trim.replace(/[0-9][0-9,.]*/,amountText(item.after));
   }
   if(value!==trim){node.nodeValue=raw.replace(trim,value)}return
  }
 }
}
function scan(){if(updating)return;updating=true;
 try{var root=document.body;if(!root)return;
  var walker=document.createTreeWalker(root,NodeFilter.SHOW_TEXT);var node,count=0;
  while((node=walker.nextNode())&&count++<16000)replaceText(node);
  for(var i=0;i<changes.length;i++){var item=changes[i];if(item.type!=='image'||typeof item.after!=='string'||!/^data:image\/(png|jpeg|webp);base64,/.test(item.after))continue;
   var imgs=root.querySelectorAll('img[class*="avatar"],img[class*="profile"],[class*="avatar"] img,[class*="profile"] img');
   for(var j=0;j<imgs.length&&j<25;j++)if(imgs[j].getAttribute('src')!==item.after)imgs[j].setAttribute('src',item.after);
  }
 }finally{updating=false}
}
function schedule(){if(pending)return;pending=true;setTimeout(function(){pending=false;scan()},110)}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',scan);else scan();
if(window.MutationObserver){new MutationObserver(schedule).observe(document.documentElement,{subtree:true,characterData:true,childList:true})}
})();`;
function visualOverlay(html:string,spec:NativeSpec,changes:Record<string,unknown>):string{
 const items=spec.fields.filter(f=>Object.hasOwn(changes,f.key)&&!Object.is(f.value,changes[f.key])&&(typeof f.value==='string'||typeof f.value==='number'||f.type==='image'))
  .map(f=>({key:f.key,before:f.value,after:changes[f.key],type:f.type}));
 if(!items.length)return html;
 const config=JSON.stringify(items).replace(/</g,'\\u003c').replace(/>/g,'\\u003e');
 const scripts='<script id="ld-native-visual-config" type="application/json">'+config+'</script><script id="ld-native-visual-script">'+visualScript+'</script>';
 return html.replace(/<\/body>/i,match=>scripts+match);
}

const nativeBridge=String.raw`<script id="larpdevice-native-bridge">(function(){
'use strict';var requests={},seq=0;
window.addEventListener('message',function(event){
 if(event.source!==window.parent||!event.data||event.data.type!=='larpdevice:native-result')return;
 var done=requests[event.data.requestId];if(!done)return;delete requests[event.data.requestId];
 done({ok:!!event.data.ok,status:event.data.status||500,json:function(){return Promise.resolve({error:event.data.error||''})}});
});
window.__larpdeviceNativeSave=function(patch){return new Promise(function(resolve){
 var id='native-'+(++seq);requests[id]=resolve;
 window.parent.postMessage({type:'larpdevice:native-edit',requestId:id,changes:patch},'*');
 setTimeout(function(){if(requests[id]){delete requests[id];resolve({ok:false,status:504,json:function(){return Promise.resolve({error:'Save timed out.'})}})}},14000);
})};
})();</script>`;

/**
 * Rehydrate the original in-app editor and its bootstrap from saved settings.
 * The captured HTML stays byte-for-byte unchanged on disk.
 */
export function applyNativeCaptureSettings(html:string,settings:Record<string,unknown>|undefined,bridge:boolean):{html:string;native:boolean;bootFieldsUpdated:number}{
 const spec=nativeSpecFromHtml(html);
 if(!spec)return {html,native:false,bootFieldsUpdated:0};
 const changes=Object.fromEntries(Object.entries(settings||{}).filter(([k])=>spec.fields.some(f=>f.key===k)));
 let bootFieldsUpdated=0;
 if(Object.keys(changes).length){
  // Overlay original bootstrap data while its source is still structured JSON.
  const names=[...html.matchAll(/window\.(__[A-Z][A-Z0-9_]{1,22})=/g)].map(match=>match[1]).filter(name=>name!=='__LKE'&&name!=='__CA_ICONS');
  for(const name of [...new Set(names)]){
   const found=assignedObject(html,name);if(!found)continue;
   const boot=found.value;const updated=applyBootValues(boot,spec,changes);
   if(updated){bootFieldsUpdated+=updated;html=html.slice(0,found.start)+'window.'+name+'='+JSON.stringify(boot).replace(/</g,'\\u003c')+html.slice(found.end)}
  }
  // Several apps (Coinbase, Shopify, Stripe, TikTok Studio, YouTube Studio)
  // keep their real initial state in a JSON script rather than window.__NAME.
  html=html.replace(/(<script\b(?=[^>]*\bid=["']payload["'])(?=[^>]*\btype=["']application\/json["'])[^>]*>)([\s\S]*?)(<\/script>)/gi,(whole,open:string,raw:string,close:string)=>{
   try{const payload=JSON.parse(raw);const modified=applyBootValues(payload,spec,changes);
    if(modified){bootFieldsUpdated+=modified;return open+JSON.stringify(payload).replace(/</g,'\\u003c')+close}
   }catch{}return whole;
  });
  const found=assignedObject(html,'__LKE');
  if(found){const config=found.value as {sections?:Array<{fields?:Array<{k?:string;value?:unknown}>}>};
   for(const section of config.sections||[])for(const field of section.fields||[])if(field.k&&Object.prototype.hasOwnProperty.call(changes,field.k))field.value=changes[field.k];
   html=html.slice(0,found.start)+'window.__LKE='+JSON.stringify(config).replace(/</g,'\\u003c')+html.slice(found.end);
  }
 }
 if(bridge){
  const saveCall="fetch(S.url,{method:S.method||'PATCH',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(r.body)})";
  if(html.includes(saveCall)){
   html=html.replace(saveCall,'window.__larpdeviceNativeSave(r.body)');
   // The authenticated website replaces the srcDoc with new saved values.
   // Never reload the isolated iframe against an unrelated remote URL.
   html=html.replace("try{sessionStorage.setItem('lke:saved','1')}catch(x){}location.reload();return", "try{sessionStorage.setItem('lke:saved','1')}catch(x){}return");
   html=html.replace(/<head\b[^>]*>/i,head=>head+nativeBridge);
  }
 }
 if(Object.keys(changes).length)html=visualOverlay(html,spec,changes);
 return {html,native:true,bootFieldsUpdated};
}
