"""Execute the real batch button with a DOM/fetch stub; no browser or network."""
from pathlib import Path
import shutil
import subprocess

import pytest


@pytest.mark.parametrize('stop_after_first', [False, True, 'manual'])
def test_button_processes_all_offers_sequentially_ignores_filters_and_keeps_partial_results(stop_after_first):
    node = shutil.which('node')
    if not node:pytest.skip('Node.js is required for the isolated UI harness')
    source = Path(__file__).resolve().parents[2]/'InvestmentManager/static/js/export_packages.js'
    harness = r"""
const fs = require('node:fs'), vm = require('node:vm'), assert = require('node:assert/strict');
const nodes = new Map();
function element() {
 return { value: '', _text: '', get textContent(){return this._text+this.children.map(x=>x.textContent).join(' ')}, set textContent(x){this._text=x;this.children=[]}, children: [], listeners: {}, disabled: false,
  classList: {add(){}, remove(){}, toggle(){}},
  append(...items){this.children.push(...items)}, replaceChildren(...items){this.children=items},
  addEventListener(type, handler){this.listeners[type]=handler} };
}
function byId(id){if(!nodes.has(id))nodes.set(id,element());return nodes.get(id)}
global.document = {getElementById: byId, createElement: element, addEventListener(){}};
byId('packages-domain').value='domestic';
byId('packages-offer').value='999'; // A visible filter must not narrow the batch.
const calls=[];let active=0;
global.fetch=async (url, options={}) => {
 assert.equal(active,0,'Overlapping batch requests');active++;
 calls.push([url,options]);let data;
 if(url.endsWith('/plan')) {
  assert.equal(options.body,'{}');data={offer_ids:['18','17','19'],total:3};
 } else if(options.method==='POST') {
  assert.equal(options.body,'{}');
  if(url.endsWith('/18')) data={sets:[{code:'preparation_failed',action:'add',message:'Synthetic failure'}]};
  else if(url.endsWith('/17')) data={sets:[process.argv[2]==='manual'
    ? {code:'manual_preparation_required',action:'add',message:'Przygotuj ręcznie nowy zestaw',portals:['no']}
    : {code:'prepared_verified',action:'add',prepared:true,verified:true}]};
  else data={sets:[],code:'no_action'};
  if(process.argv[2]==='stop')byId('domestic-batch-stop').listeners.click();
  if(data.sets.length)data.code='processed';
 } else data={items:[],total:0,notice:'synthetic'};
 return {ok:true,async json(){await Promise.resolve();active--;return data}};
};
vm.runInThisContext(fs.readFileSync(process.argv[1],'utf8'));
assert.equal(calls.length,0,'Batch must require a click');
(async()=>{
 await byId('domestic-batch-start').listeners.click();
 const posts=calls.filter(([,o])=>o.method==='POST').map(([u])=>u.split('/').pop());
 assert.deepEqual(posts, process.argv[2]==='stop' ? ['plan','18'] : ['plan','18','17','19']);
 const summary=byId('domestic-batch-summary').textContent;
 assert(summary.includes('Błędy wykonania: 1'));
 assert(summary.includes(process.argv[2]==='stop' ? 'Przeanalizowano: 1/3' : 'Przeanalizowano: 3/3'));
 assert.equal(byId('domestic-batch-start').disabled,false);
 assert(byId('domestic-batch-results').children[0].textContent.includes('Synthetic failure'));
 if(process.argv[2]==='all')assert(summary.includes('Przygotowane zestawy: 1. Zweryfikowane istniejące zestawy: 0.'));
 if(process.argv[2]==='manual') {
  assert(summary.includes('Wymagające interwencji operatora: 1'));
  assert(byId('domestic-batch-results').children[1].textContent.includes('Przygotuj ręcznie nowy zestaw'));
 }
})().catch(error=>{console.error(error);process.exitCode=1});
"""
    mode = 'manual' if stop_after_first == 'manual' else 'stop' if stop_after_first else 'all'
    completed = subprocess.run([node, '-e', harness, str(source), mode],
                               capture_output=True, text=True, encoding='utf-8', timeout=15)
    assert completed.returncode == 0, completed.stderr


@pytest.mark.parametrize('scenario', ['disconnect', 'malformed', 'pending', 'mixed', 'restart', 'limits'])
def test_confirmed_progress_interventions_and_restart(scenario):
    node = shutil.which('node')
    if not node:pytest.skip('Node.js is required for the isolated UI harness')
    source = Path(__file__).resolve().parents[2]/'InvestmentManager/static/js/export_packages.js'
    harness = 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(){return {value:'',_text:'',get textContent(){return this._text+this.children.map(x=>x.textContent).join(' ')},set textContent(x){this._text=x;this.children=[]},children:[],listeners:{},disabled:false,
 classList:{add(){},remove(){},toggle(){}},append(...x){this.children.push(...x)},
 replaceChildren(...x){this.children=x},addEventListener(t,f){this.listeners[t]=f}}}
const byId=id=>{if(!nodes.has(id))nodes.set(id,element());return nodes.get(id)};
global.document={getElementById:byId,createElement:element,addEventListener(){}};
byId('packages-domain').value='domestic';byId('packages-offer').value='999';
const ids=scenario==='mixed'?['1','2','3','4','5','6','7','8']:scenario==='limits'?['1','2','3','4']:['1','2'];
const samples={
 '1':{code:'prepared_verified',prepared:true,verified:true},
 '2':{code:'verified',verified:true},'3':{code:'current',skipped_current:true},
 '4':{code:'manual_preparation_required',message:'MANUAL_ACK'},
 '5':{code:'needs_intervention',reasons:['MANUAL_QUEUE']},
 '6':{code:'preparation_failed',message:'EXECUTION_ERROR'},'8':{code:'no_action'}
};
let release,active=0,first=true,run=0;
global.fetch=async(url,options={})=>{
 assert.equal(active,0);active++;calls.push(url);
 let data;
 if(url.endsWith('/plan')){run++;data={offer_ids:ids,total:ids.length}}
 else if(options.method==='POST'){
  const id=url.split('/').pop();
  if(scenario==='pending'&&id==='1'&&first){
   first=false;await new Promise(resolve=>release=resolve);
  }
  if((['disconnect','restart'].includes(scenario)&&id==='1'&&first)||scenario==='mixed'&&id==='7'){
   first=false;if(scenario==='restart')byId('domestic-batch-stop').listeners.click();
   active--;throw new Error('SYNTHETIC_CONNECTION_LOST');
  }
  if(scenario==='malformed'&&id==='1')data={code:'processed',sets:[{code:'prepared_verified'},null]};
  else {
   const row=scenario==='limits'?{code:['budget_exhausted','lock_busy','database_limit','network_timeout'][Number(id)-1],
      stage:'safe_stage',message:'STOP_'+id,prepared:id==='1'}:scenario==='mixed'?samples[id]:scenario==='restart'&&run===2&&id==='1'
      ?{code:'current',skipped_current:true}:{code:'prepared_verified',prepared:true,verified:true};
   data={code:'processed',sets:[{...row,action:'add'}]};
  }
 }else data={items:[],total:0,notice:'synthetic'};
 return {ok:true,async json(){active--;return data}};
};
vm.runInThisContext(fs.readFileSync(process.argv[1],'utf8'));
const summary=()=>byId('domestic-batch-summary').textContent;
const flush=async()=>{for(let i=0;i<4;i++)await new Promise(setImmediate)};
(async()=>{
 assert.equal(calls.length,0);
 const start=byId('domestic-batch-start').listeners.click;
 const work=start();await flush();
 if(scenario==='pending'){
  assert(summary().includes('Zaplanowano: 2'));assert(summary().includes('Przeanalizowano: 0/2'));
  assert(summary().includes('Niepotwierdzone operacje: 0'));assert.equal(calls.length,2);release();
 }
 await work;
 if(['disconnect','malformed'].includes(scenario)){
  assert(summary().includes('Przeanalizowano: 1/2'));assert(summary().includes('Niepotwierdzone operacje: 1'));
  assert(summary().includes('Wyniki nie są kompletne'));assert(summary().includes('Błędy wykonania: 0'));
  assert.equal(byId('domestic-batch-results').children.length,2);
 }
 if(scenario==='pending')assert(summary().includes('Przeanalizowano: 2/2'));
 if(scenario==='mixed'){
  assert(summary().includes('Przeanalizowano: 7/8'));assert(summary().includes('Niepotwierdzone operacje: 1'));
  assert(summary().includes('Przygotowane zestawy: 1'));assert(summary().includes('Zweryfikowane istniejące zestawy: 1'));
  assert(summary().includes('Pominięte aktualne: 1'));assert(summary().includes('Wymagające interwencji operatora: 2'));
  assert(summary().includes('Błędy wykonania: 1'));
  const output=byId('domestic-batch-results').children.map(x=>x.textContent).join('\n');
  for(const detail of ['#4','MANUAL_ACK','#5','MANUAL_QUEUE','#6','EXECUTION_ERROR','#7','SYNTHETIC_CONNECTION_LOST'])assert(output.includes(detail));
 }
 if(scenario==='restart'){
  assert(summary().includes('Przeanalizowano: 0/2'));assert(summary().includes('Niepotwierdzone operacje: 1'));
  await start();assert(summary().includes('Przeanalizowano: 2/2'));assert(summary().includes('Niepotwierdzone operacje: 0'));
  assert(summary().includes('Pominięte aktualne: 1'));
 }
 if(scenario==='limits'){
  assert(summary().includes('Przeanalizowano: 4/4'));assert(summary().includes('Błędy wykonania: 4'));
  assert(summary().includes('Przygotowane zestawy: 1'));assert(summary().includes('Zweryfikowane istniejące zestawy: 0'));
  const output=byId('domestic-batch-results').children.map(x=>x.textContent).join('\n');
  for(const message of ['wyczerpano budżet kooperatywny','zajęta blokada','limit bazy 64 MiB','timeout sieciowy','Etap: safe_stage.'])assert(output.includes(message));
 }
 assert.equal(byId('domestic-batch-start').disabled,false);
})().catch(error=>{console.error(error);process.exitCode=1});
"""
    result = subprocess.run([node, '-e', harness, str(source), scenario], capture_output=True,
                            text=True, encoding='utf-8', timeout=15)
    assert result.returncode == 0, result.stderr
