"""Real frontend, controlled clocks and DOM; no browser/server/network."""
from pathlib import Path
import shutil
import subprocess

import pytest


@pytest.mark.parametrize('scenario', ['timings', 'missing', 'malformed', 'incomplete', 'clock_failure', 'refresh_failure'])
def test_monitoring_preserves_counters_results_and_request_flow(scenario):
    executable = shutil.which('node')
    if not executable:
        pytest.skip('Node unavailable')
    source = Path(__file__).resolve().parents[2]/'InvestmentManager/static/js/export_packages.js'
    script = r"""
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
const scenario=process.argv[2], nodes=new Map(), calls=[];
function element(tag){return {tag,value:'',_text:'',children:[],listeners:{},disabled:false,
 get textContent(){return this._text+this.children.map(x=>x.textContent).join(' ')},
 set textContent(x){this._text=String(x);this.children=[]},
 classList:{add(){},remove(){},toggle(){}},append(...x){this.children.push(...x)},
 replaceChildren(...x){this._text='';this.children=x},addEventListener(t,f){this.listeners[t]=f}}}
function byId(id){if(!nodes.has(id))nodes.set(id,element(id));return nodes.get(id)}
global.document={getElementById:byId,createElement:element,addEventListener(){}};
byId('packages-domain').value='domestic';
let now=0,tick,cleared=0,active=0,release;
global.performance={now(){if(scenario==='clock_failure')throw new Error('clock');return now}};
global.setInterval=f=>{tick=f;return 42};global.clearInterval=id=>{assert.equal(id,42);cleared++};
global.fetch=async(url,options={})=>{
 assert.equal(active,0,'No parallel batch requests');active++;calls.push([url,options]);
 let data;
 if(url.endsWith('/plan')){now+=200;data={offer_ids:['1','2','3','4','5','6'],total:6}}
 else if(options.method==='POST'){
  const id=Number(url.split('/').pop());
  if(id===4)await new Promise(r=>release=r);
  now+=id*1000;
  if(id===6){active--;throw new Error('NETWORK_UNKNOWN')}
  const rows={1:[{code:'prepared_verified',action:'add',prepared:true,verified:true},
      {code:'preparation_failed',action:'delete',message:'PARTIAL_DELETE'}],
   2:[{code:'verified',verified:true,action:'add'}],3:[{code:'current',skipped_current:true,action:'add'}],
   4:[{code:'needs_intervention',message:'MANUAL',action:'add'}, {code:'unresolved_operation',action:'delete'}],
   5:[{code:'no_action'}]};
  data={offer_id:id,sets:rows[id],code:'processed'};
  if(scenario!=='missing')data.timings=scenario==='malformed'?{version:1,total_ms:'invalid',stages:[null]}:
   {version:1,total_ms:100,completed:scenario!=='incomplete',stages:[
    {id:0,parent_id:null,name:'prepare_set',action:'add',elapsed_ms:90,completed:true},
    {id:1,parent_id:0,name:'prepare_portal',action:'add',portal:'no',elapsed_ms:70,completed:scenario!=='incomplete'}]};
 } else {
  now+=1200;
  if(scenario==='refresh_failure'){active--;throw new Error('REFRESH_FAILED')}
  data={items:[],total:0,notice:'test'};
 }
 return {ok:true,async json(){active--;return data}};
};
const flush=async()=>{for(let i=0;i<4;i++)await new Promise(setImmediate)};
vm.runInThisContext(fs.readFileSync(process.argv[1],'utf8'));
(async()=>{
 assert.equal(calls.length,0,'Manual click required');
 const work=byId('domestic-batch-start').listeners.click();await flush();
 assert(byId('domestic-batch-summary').textContent.includes('Przeanalizowano: 3/6'));
 const before=calls.length;now+=500;tick();assert.equal(calls.length,before,'Timer must not poll');
 const current=byId('domestic-batch-current').textContent;
 assert(current.includes('#4'));
 if(scenario!=='clock_failure'){
  assert(current.includes('0.50 s'));
  assert(byId('domestic-batch-time').textContent.includes('około 5.50 s'));
 }
 release();await work;
 const summary=byId('domestic-batch-summary').textContent;
 for(const text of ['Przeanalizowano: 5/6','Niepotwierdzone operacje: 1','Przygotowane zestawy: 1',
  'Zweryfikowane istniejące zestawy: 1','Pominięte aktualne: 1','nierozstrzygniętymi operacjami: 1',
  'interwencji operatora: 1','Bez potrzeby operacji: 1','Błędy wykonania: 1'])assert(summary.includes(text),text);
 const rows=byId('domestic-batch-results').children;assert.equal(rows.length,6);
 assert(rows[0].textContent.includes('add:'));assert(rows[0].textContent.includes('delete:'));
 assert(rows[0].textContent.includes('PARTIAL_DELETE'));assert(rows[5].textContent.includes('NETWORK_UNKNOWN'));
 assert(rows[0].textContent.includes('Częściowy wynik'));
 assert.equal(byId('domestic-batch-counts').children.length,10);
 const detail=rows[0].textContent;
 if(['missing','malformed'].includes(scenario))assert(detail.includes('pomiar backendu niedostępny'));
 else {
  assert(detail.includes('nie należy ich sumować'));
  assert(detail.includes(scenario==='incomplete'?'pomiar niekompletny':'pomiar kompletny'));
  assert(detail.includes(scenario==='incomplete'?'brak pomiaru / etap':'nie wykonywano'));
 }
 const metric=byId('domestic-batch-time').textContent;
 if(scenario!=='clock_failure'){
  assert(metric.includes('21.70 s'),'Batch excludes refresh');
  assert(metric.includes('3.58 s'),'Average includes failed request');
  assert(byId('domestic-batch-refresh').textContent.includes('1.20 s'));
  byId('domestic-batch-sort').value='slowest';byId('domestic-batch-sort').listeners.change();
  assert.equal(byId('domestic-batch-results').children[0].children[0].textContent,'#6');
 }else assert(metric.includes('brak pomiaru'));
 assert.equal(cleared,1);
 assert(byId('domestic-batch-current').textContent.includes('Brak bieżącego'));
 assert(metric.includes('przebieg zakończony'));
 assert.equal(calls.filter(([,o])=>o.method==='POST').length,7);
 assert.equal(calls.filter(([,o])=>!o.method).length,1,'Only the existing final refresh');
 if(scenario==='refresh_failure')assert(byId('domestic-batch-refresh').textContent.includes('błąd odświeżenia'));
 assert.equal(byId('domestic-batch-start').disabled,false);
})().catch(e=>{console.error(e);process.exitCode=1});
"""
    result = subprocess.run([executable, '-e', script, str(source), scenario],
                            text=True, capture_output=True, encoding='utf-8', timeout=15)
    assert result.returncode == 0, result.stderr
