"""Configured card fields and compact legends; all HTTP is stubbed."""
import json
from pathlib import Path
import re
import shutil
import subprocess

import pytest
from InvestmentManager import form_config

ROOT = Path(__file__).resolve().parents[2]
JS = ROOT / 'InvestmentManager/static/js/offers_cards.js'


def configuration():
    template = (ROOT / 'InvestmentManager/templates/investmentmanager/components/add_offer.html').read_text(encoding='utf8')
    bindings = re.findall(r'"([^"]+)":\s*{{\s*(\w+)\s*\|\s*tojson\s*}}', template)
    assert bindings
    return {name: getattr(form_config, variable) for name, variable in bindings}


HARNESS = r'''
const fs=require('node:fs'),path=require('node:path'),vm=require('node:vm'),assert=require('node:assert/strict');
const config=JSON.parse(process.argv[2]),scenario=process.argv[3],type=process.argv[4];
class Element{
 constructor(tag){this.tag=tag;this.children=[];this.listeners={};this.style={};this.dataset={};this._text='';
  const set=new Set(['hidden']);this.classList={contains:x=>set.has(x),add:(...x)=>x.forEach(v=>set.add(v)),remove:(...x)=>x.forEach(v=>set.delete(v)),toggle(x,on){if(on)set.add(x);else set.delete(x)}}}
 set textContent(x){this._text=String(x);this.children=[]}get textContent(){return this._text+this.children.map(x=>x.textContent).join(' ')}
 set innerHTML(x){this._html=x;this.children=[]}get innerHTML(){return this._html||''}
 appendChild(x){x.parentElement=this;this.children.push(x)}append(...x){x.forEach(v=>this.appendChild(v))}
 remove(){const p=this.parentElement;if(p)p.children.splice(p.children.indexOf(this),1)}
 replaceWith(x){const p=this.parentElement;p.children[p.children.indexOf(this)]=x;x.parentElement=p}
 insertBefore(x,before){x.parentElement=this;this.children.splice(this.children.indexOf(before),0,x)}
 replaceChildren(...xs){this.children=[];xs.forEach(x=>this.appendChild(x))}
 addEventListener(t,f){this.listeners[t]=f}querySelector(){return null}contains(x){return this.children.includes(x)}
 closest(selector){return selector.includes('.ignore-card-click')&&(this.className||'').split(' ').includes('ignore-card-click')?this:this.parentElement?.closest(selector)||null}
}
global.window={OffersCore:{state:{}},ADD_OFFER_FORM_FIELDS:config};global.document={createElement:t=>new Element(t)};
const source=fs.readFileSync(process.argv[1],'utf8');
if(scenario!=='fallback'){
 const edit=fs.readFileSync(path.join(path.dirname(process.argv[1]),'offers_edit.js'),'utf8');
 vm.runInThisContext(edit.match(/const offersEditFieldLabels = \{[\s\S]*?\n\};/)[0]);
}
vm.runInThisContext(source);
renderOfferGallery=()=>{};animateDetailsExpand=x=>x.classList.remove('hidden');animateDetailsCollapse=x=>x.classList.add('hidden');
const walk=x=>[x,...x.children.flatMap(walk)];
const filled=t=>Object.assign(Object.fromEntries(config[t].map(f=>[f,'1'])),{ID:17,Typ_nieruchomosci:t,Status_oferty:'aktywna',Portal_sync:{}});
function render(offer){
 const before=JSON.stringify(offer),cfg=JSON.stringify(config),calls=[];
 global.fetch=async(url,options={})=>{calls.push([url,options]);return {ok:true,text:async()=>'',json:async()=>[]}};
 const root=new Element('div'),card={querySelector:()=>root},arrow=new Element('span'),thumb=new Element('img'),wrapper=new Element('div');
 toggleDetails(card,offer,arrow,thumb,wrapper);
 assert.equal(JSON.stringify(offer),before);assert.equal(JSON.stringify(config),cfg);
 assert.equal(calls.length,1);assert(calls.every(x=>x[0]==='/crm/leadhunter/reverse_match_leads'));
 const cells=walk(root).filter(x=>x.dataset.offerField),byField=Object.fromEntries(cells.map(x=>[x.dataset.offerField,x]));
 const legend=walk(root).find(x=>x.dataset.offerReviewLegend==='true');
 assert(!walk(root).some(x=>x.tag==='ul'||x.tag==='summary'||x.textContent==='Pozosta\u0142e dane:'));
 if(legend){assert.equal(legend.style.fontSize,'11px');assert.equal(legend.style.display,'flex');assert.equal(legend.style.flexWrap,'wrap')}
 return {root,card,arrow,thumb,wrapper,cells,byField,legend,calls};
}
const value=cell=>cell.children[1].textContent;
if(scenario==='fields'){
 const offer=filled(type);config[type].forEach((field,i)=>offer[field]=[null,'nd',0][i%3]);
 const r=render(offer);assert.deepEqual(r.cells.map(x=>x.dataset.offerField),config[type].filter(f=>f!=='Powiat'));
 config[type].forEach((field,i)=>{
  if(field==='Powiat')return;
  const cell=r.byField[field],area=field.toLowerCase().startsWith('powierzchnia');
  assert.equal(cell.style.padding,'5px 7px');assert.equal(cell.children[0].style.fontSize,'9px');assert.equal(cell.children[1].style.fontSize,'12px');
  if(field==='Wojewodztwo'){
   assert.equal(value(cell),String(offer.Wojewodztwo??'')+'\n'+String(offer.Powiat??''));
   assert.equal(cell.children[0].textContent,'Wojew\u00f3dztwo / powiat');return;
  }
  if(i%3===0)assert.equal(value(cell),'');if(i%3===1)assert.equal(value(cell),'nd');if(i%3===2)assert(value(cell).startsWith('0'));
  assert.equal(cell.children[1].style.color,area?'#b91c1c':i%3===2?'#0f172a':'#92400e');
 });
}else if(scenario==='complete'){
 const r=render(filled(type));assert(!r.legend);assert(r.cells.every(x=>x.style.background==='#f8fafc'));
}else if(scenario==='values'){
 for(const missing of [null,undefined,'','   ']){
  const r=render({...filled('Dom'),Gmina:missing,Ulica:'',Powierzchnia:missing});
  assert.equal(value(r.byField.Gmina),'');assert.equal(value(r.byField.Ulica),'');assert.equal(value(r.byField.Powierzchnia),'');
 }
 for(const nd of ['nd',' ND ','nD']){
  const r=render({...filled('Dom'),Gmina:nd,Powierzchnia:nd});assert.equal(value(r.byField.Gmina),nd.trim());
 }
 for(const zero of [0,'0','0.00','0,00','-0']){
  const r=render({...filled('Mieszkanie'),Powierzchnia:zero,Pietro:zero});
  assert.equal(r.byField.Powierzchnia.style.background,'#fef2f2');assert.equal(r.byField.Pietro.style.background,'#f8fafc');
 }
}else if(scenario==='optional_only'){
 const r=render({...filled('Dom'),Gmina:'nd',Ulica:null});
 assert.equal(value(r.byField.Gmina),'nd');assert.equal(value(r.byField.Ulica),'');assert.equal(r.legend.children.length,1);
 assert.equal(r.legend.children[0].textContent,'\u017b\u00f3\u0142te pola \u2014 opcjonalne dane do uzupe\u0142nienia.');
 assert.equal(r.legend.children[0].style.color,'#92400e');assert(r.legend.textContent.includes('opcjonalne'));assert(!r.legend.textContent.includes('portale'));
}else if(scenario==='required_only'){
 const r=render({...filled('Dom'),Powierzchnia:0});assert.equal(r.legend.children.length,1);
 assert.equal(r.legend.children[0].textContent,'Czerwone pola \u2014 wymagane przez portale zewn\u0119trzne.');
 assert.equal(r.legend.children[0].style.color,'#b91c1c');assert(r.legend.textContent.includes('portale'));
}else if(scenario==='both'){
 const r=render({...filled('Dom'),Powierzchnia:null,Gmina:'nd'});assert.equal(r.legend.children.length,2);
 assert.equal(r.legend.children[0].style.color,'#b91c1c');assert.equal(r.legend.children[1].style.color,'#92400e');
}else if(scenario==='unknown'){
 global.fetch=()=>{throw new Error('Unexpected HTTP')};assert.equal(createOfferDataReview({Typ_nieruchomosci:'Unknown',Powierzchnia:0}),null);
 delete window.ADD_OFFER_FORM_FIELDS;assert.equal(createOfferDataReview(filled('Dom')),null);
}else if(scenario==='dynamic'||scenario==='fallback'){
 config.Dom.push('Nowe_pole_formularza');const r=render({...filled('Dom'),Nowe_pole_formularza:null});
 assert(r.byField.Nowe_pole_formularza);assert.equal(value(r.byField.Nowe_pole_formularza),'');
}else if(scenario==='safe'){
 const injected='<img src=x onerror=alert(1)>';config.Dom.push(injected);
 const r=render({...filled('Dom'),[injected]:injected}),cell=r.byField[injected];
 assert.equal(cell.children[0].textContent,injected);assert.equal(value(cell),injected);assert(cell.children.every(x=>!x.innerHTML&&x.tag!=='img'));
}else if(scenario==='address'){
 global.fetch=()=>{throw new Error('Address must not fetch data')};
 const address=offer=>createOfferCardAddress(offer);
 const base={Wojewodztwo:'opolskie',Miejscowosc:'K\u0119dzierzyn-Ko\u017ale',Ulica:'Czeremchowa',Lokalizacja:'Centrum',Gmina:'Not part of address'};
 const box=address(base);assert.equal(box.children[0].textContent,'opolskie \u00b7 K\u0119dzierzyn-Ko\u017ale \u00b7 Czeremchowa');
 assert.equal(box.children[1].textContent,'Lokalizacja: Centrum');
 for(const empty of [null,undefined,'','  ','nd',' ND ']){
  const result=address({...base,Ulica:empty,Lokalizacja:empty});
  assert.equal(result.children.length,1);assert.equal(result.children[0].textContent,'opolskie \u00b7 K\u0119dzierzyn-Ko\u017ale');
 }
 assert.equal(address({...base,Lokalizacja:' K\u0119dzierzyn-Ko\u017ale '}).children.length,1);
 assert.equal(address({Wojewodztwo:null,Miejscowosc:'nd',Ulica:'',Lokalizacja:'ND'}),null);
 assert.equal(address({Lokalizacja:'Centrum'}).children[0].textContent,'Lokalizacja: Centrum');
 const injected='<img src=x onerror=alert(1)>',safe=address({Ulica:injected,Lokalizacja:injected+'x'});
 assert(safe.children.every(x=>!x.innerHTML&&x.tag==='p'));assert.equal(safe.children[0].textContent,injected);
}else if(scenario==='region_pair'){
 const callbacks={};global.enableOfferInlineEdit=(cell,content,offer,field,onSaved)=>{callbacks[field]=onSaved};
 const offer={...filled('Dom'),Wojewodztwo:'opolskie',Powiat:'krapkowicki'},r=render(offer);
 const cell=r.byField.Wojewodztwo;
 assert(!r.byField.Powiat);assert(!callbacks.Powiat);assert(callbacks.Wojewodztwo);
 assert.equal(value(cell),'opolskie\nkrapkowicki');assert.equal(cell.style.background,'#f8fafc');
 for(const district of ['',null,'nd']){
  offer.Powiat=district;callbacks.Wojewodztwo();assert.equal(cell.style.background,'#fffbeb');
  assert.equal(value(cell),'opolskie\n'+(district??''));
 }
 offer.Wojewodztwo='new';offer.Powiat='district';callbacks.Wojewodztwo();
 assert.equal(value(cell),'new\ndistrict');assert.equal(cell.style.background,'#f8fafc');assert.equal(r.calls.length,1);
}else if(scenario==='inplace'){
 const callbacks={};global.enableOfferInlineEdit=(cell,content,offer,field,onSaved)=>{callbacks[field]=onSaved};
 const offer={...filled('Dom'),Powierzchnia:0,Gmina:''},r=render(offer);
 const cells=[...r.cells],panel=r.byField.Powierzchnia.parentElement.parentElement;
 panel.scrollTop=85;let summaries=0;r.card.refreshInlineSummary=()=>summaries++;
 offer.Powierzchnia=120;const target=callbacks.Powierzchnia();
 assert.equal(target,r.byField.Powierzchnia);assert.equal(panel.scrollTop,85);
 assert.deepEqual(walk(r.root).filter(x=>x.dataset.offerField),cells);
 assert.equal(r.byField.Powierzchnia.style.background,'#f8fafc');assert(value(target).includes('120'));
 assert.equal(summaries,1);assert.equal(r.calls.length,1);assert(!r.root.classList.contains('hidden'));
 assert.equal(walk(r.root).find(x=>x.dataset.offerReviewLegend).children.length,1);
 offer.Gmina='filled';callbacks.Gmina();assert(!walk(r.root).some(x=>x.dataset.offerReviewLegend));
 offer.Powierzchnia=0;callbacks.Powierzchnia();assert(walk(r.root).some(x=>x.dataset.offerReviewLegend));
 assert.equal(r.calls.length,1);
}else if(scenario==='interaction'){
 const offer={...filled('Dom'),Powierzchnia:null,Powierzchnia_dzialki:'nd'},r=render(offer);assert(r.legend);
 const body=source.match(/card\.addEventListener\('click', \(e\) => \{([\s\S]*?)\n    \}\);/)[1];
 const click=new Function('e','card','offer','arrow','thumbRef','thumbWrapper','toggleDetails',body);
 const detailClass=source.match(/details\.className = '([^']+)'/)[1];
 assert(detailClass.split(' ').includes('ignore-card-click'));r.root.className=detailClass;
 for(const target of walk(r.root))click({target},r.card,offer,r.arrow,r.thumb,r.wrapper,toggleDetails);
 for(const target of [...walk(r.legend),...r.cells.flatMap(walk)])click({target},r.card,offer,r.arrow,r.thumb,r.wrapper,toggleDetails);
 assert(!r.root.classList.contains('hidden'));assert.equal(r.calls.length,1);
 assert(!walk(r.root).some(x=>x.tag==='button'&&x.textContent==='Edytuj'));
 toggleDetails(r.card,offer,r.arrow,r.thumb,r.wrapper);assert(r.root.classList.contains('hidden'));
 offer.Powierzchnia='120';offer.Powierzchnia_dzialki='500';toggleDetails(r.card,offer,r.arrow,r.thumb,r.wrapper);
 assert(!r.root.classList.contains('hidden'));assert(!walk(r.root).some(x=>x.dataset.offerReviewLegend));
}else throw new Error('Unknown scenario');
'''


@pytest.mark.parametrize('property_type', list(configuration()))
@pytest.mark.parametrize('scenario', ['fields', 'complete'])
def test_fields_match_actual_form_configuration(property_type, scenario):
    run(scenario, property_type)


@pytest.mark.parametrize('scenario', ['values', 'optional_only', 'required_only', 'both', 'unknown', 'dynamic', 'fallback', 'safe', 'address', 'interaction', 'inplace', 'region_pair'])
def test_values_and_interaction(scenario):
    run(scenario)


def run(scenario, property_type='Dom'):
    executable = shutil.which('node')
    if not executable:
        pytest.skip('Node unavailable')
    result = subprocess.run([executable, '-e', HARNESS, str(JS), json.dumps(configuration()), scenario, property_type],
                            capture_output=True, text=True, encoding='utf8', timeout=15)
    assert result.returncode == 0, result.stderr
