"""Actual edit renderer preserves stored nd without inventing missing values."""
import json
from pathlib import Path
import shutil
import subprocess

import pytest
from InvestmentManager.form_config import flat_apartment_form_fields


@pytest.mark.parametrize('value', ['nd', '', None, 0, '0', 'Miejskie'])
@pytest.mark.parametrize('options_contain_nd', [False, True])
def test_edit_displays_saved_values_in_text_and_select(value, options_contain_nd):
    executable = shutil.which('node')
    if not executable:
        pytest.skip('Node unavailable')
    source = Path(__file__).resolve().parents[2] / 'InvestmentManager/static/js/offers_edit.js'
    script = r'''
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
const data=JSON.parse(process.argv[2]),fields=JSON.parse(process.argv[3]);
class Element{
 constructor(tag){this.tag=tag;this.children=[];this._value='';this._selected=false;this.listeners={};}
 set value(v){this._value=String(v);if(this.tag==='select')this.children.forEach(c=>c._selected=c.value===this._value)}
 get value(){if(this.tag==='select')return (this.children.find(c=>c.selected)||this.children[0])?.value||'';return this._value}
 set selected(v){this._selected=v;if(v&&this.parent)this.parent.children.forEach(c=>{if(c!==this)c._selected=false})}
 get selected(){return this._selected}
 appendChild(x){x.parent=this;if(x.selected)this.children.forEach(c=>c._selected=false);this.children.push(x)}
 set innerHTML(v){this.children=[]}
 addEventListener(t,f){this.listeners[t]=f}
}
const form=new Element('form');global.document={createElement:t=>new Element(t)};
global.editById=id=>id==='edit-form'?form:null;
global.offersEditFormFieldMap={Mieszkanie:fields};global.offersEditFieldLabels={};global.offersEditFormatSelectLabel=v=>v;
const options=['Miejskie','Gazowe'];if(data.optionsContainNd)options.push('nd');
const calls=[];global.fetch=async url=>{calls.push(url);return {ok:true,json:async()=>({Ogrzewanie:options})}};
const source=fs.readFileSync(process.argv[1],'utf8');
vm.runInThisContext(source.slice(source.indexOf('async function renderEditFieldsComplete('),source.indexOf('function closeOfferMediaModal(')));
(async()=>{
 const offer=Object.assign(Object.fromEntries(fields.map(f=>[f,'1'])),{ID:17,Typ_nieruchomosci:'Mieszkanie',Gmina:data.value,Ulica:data.value,Pietro:data.value,Ogrzewanie:data.value});
 const before=JSON.stringify(offer);await renderEditFieldsComplete(offer);assert.equal(JSON.stringify(offer),before);
 const inputs=form.children.map(w=>w.children[1]);assert.deepEqual(inputs.map(x=>x.name),fields);
 for(const field of ['Gmina','Ulica','Pietro'])assert.equal(inputs.find(x=>x.name===field).value,data.value===null?'':String(data.value));
 const select=inputs.find(x=>x.name==='Ogrzewanie');
 if(data.value==='nd'){
  assert.equal(select.value,'nd');assert.equal(select.children.filter(x=>x.value==='nd').length,1);
 }else if(data.value==='Miejskie')assert.equal(select.value,'Miejskie');
 else assert.equal(select.value,'');
 assert.deepEqual(calls,['/crm/offers/options/Mieszkanie']);
})().catch(e=>{console.error(e);process.exit(1)});
'''
    result = subprocess.run([executable, '-e', script, str(source), json.dumps({'value': value, 'optionsContainNd': options_contain_nd}),
                             json.dumps(flat_apartment_form_fields)], capture_output=True, text=True, encoding='utf8', timeout=15)
    assert result.returncode == 0, result.stderr
