"""Execute actual frontend with a DOM, fetch and clock stub; no network."""
from pathlib import Path
import shutil
import subprocess

import pytest


@pytest.mark.parametrize('scenario', ['outcomes', 'pending', 'timeout', 'malformed', 'mismatch',
                                     'stop', 'restart', 'refresh_failure', 'refresh_pending',
                                     'bad_plan', 'duplicate_plan', 'empty', 'bad_timing', 'clock_failure',
                                     'rejected', 'gateway', 'long_request', 'blocked_success'])
def test_foreign_batch_flow(scenario):
    executable = shutil.which('node')
    if not executable:
        pytest.skip('Node required for isolated frontend harness')
    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:'',children:[],listeners:{},disabled:false,_text:'',
 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.children=x;this._text=''},addEventListener(t,f){this.listeners[t]=f}}}
const 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='foreign';byId('packages-offer').value='999';byId('packages-portal').value='domiporta';
let now=0, tick, cleared=0, active=0, release, releaseRefresh, run=0;
global.performance={now(){if(scenario==='clock_failure')throw new Error('clock unavailable');return now}};
global.setInterval=f=>{tick=f;return 17};global.clearInterval=id=>{assert.equal(id,17);cleared++};
const outcomes=['prepared','verified','skipped_current','no_action','blocked','needs_intervention','error'];
const units=Array.from({length:8},(_,i)=>({key:i===0?['cyprus_development',7,'tabelaofert','add']
 :['foreign_offer',100+i,'domiporta',i===3?'delete':'add'],category:i===3?'withdraw':i%2?'update':'new',
 members:i===0?[11,13,15]:[100+i],trigger_offer_ids:i===0?[11,15]:[100+i]}));
const flush=async()=>{for(let i=0;i<5;i++)await new Promise(setImmediate)};
global.fetch=async(url, options={})=>{
 assert.equal(active,0,'Overlapping HTTP operations');active++;calls.push([url,options]);
 let data, status=200;
 if(url.endsWith('/plan')){
  assert.deepEqual(JSON.parse(options.body),{});run++;now+=200;
  data={version:1,total:scenario==='empty'?0:8,units:scenario==='empty'?[]:units};
  if(scenario==='bad_plan')data.total=9;
  if(scenario==='duplicate_plan')data.units=[units[0],units[0],...units.slice(2)];
 }else if(options.method==='POST'){
  assert(url.endsWith('/foreign-batch/unit'),'No transport or manual generation endpoint');
  const body=JSON.parse(options.body);assert.deepEqual(Object.keys(body),['key']);
  const i=units.findIndex(u=>JSON.stringify(u.key)===JSON.stringify(body.key));assert(i>=0);
  if(['pending','long_request'].includes(scenario)&&i===3)await new Promise(resolve=>release=resolve);
  if(['stop','restart'].includes(scenario)&&i===0&&run===1)byId('foreign-batch-stop').listeners.click();
  now+=(i+1)*1000;
  if(i===7 || (['timeout','restart'].includes(scenario)&&i===0&&run===1)){
   active--;const e=new Error('SYNTHETIC_TIMEOUT');e.name='TimeoutError';throw e;
  }
  data={key:body.key,outcome:outcomes[i],reason:'synthetic_reason',package_id:'a'.repeat(32),members:units[i].members,
   verification:{state:i<3?'READY':'BLOCKED',reasons:[]},
   timings:{total:{seconds:.7,complete:true},preparation:{seconds:.5,complete:i!==5}}};
  if(scenario==='malformed'&&i===0)data.outcome='unknown';
  if(scenario==='mismatch'&&i===0)data.key=units[1].key;
  if(scenario==='blocked_success'&&i===0)data.verification.state='BLOCKED';
  if(scenario==='bad_timing')data.timings={total:{seconds:'bad',complete:true},preparation:null};
  if(['rejected','gateway'].includes(scenario)&&i===0){status=scenario==='rejected'?400:503;data={error:'REQUEST_REJECTED'}}
 }else if(url.startsWith('/crm/foreign-offers/list?')){
  data={developments:[]};
 }else{
  assert(url.includes('domain=foreign'));now+=1200;
  if(scenario==='refresh_pending')await new Promise(resolve=>releaseRefresh=resolve);
  if(scenario==='refresh_failure'){active--;throw new Error('REFRESH_FAILURE')}
  data={items:[],total:0,notice:'test metadata'};
 }
 return {ok:status===200,status,async json(){active--;return data}};
};
vm.runInThisContext(fs.readFileSync(process.argv[1],'utf8'));
const value=label=>{const card=byId('foreign-batch-counts').children.find(c=>c.children[1].textContent===label);assert(card,label);return Number(card.children[0].textContent)};
(async()=>{
 assert.equal(calls.length,0,'A deliberate click is required');
 const start=byId('foreign-batch-start').listeners.click;
 const work=start();await flush();
 if(['pending','long_request'].includes(scenario)){
  assert.equal(value('Potwierdzone'),3);assert.equal(value('Niepotwierdzone'),0);
  const count=calls.length;now+=scenario==='pending'?500:61000;tick();assert.equal(calls.length,count,'Timer must not poll');
  assert(byId('foreign-batch-current').textContent.includes('#103'));
  assert(byId('foreign-batch-current').textContent.includes(scenario==='pending'?'0.50 s':'61.00 s'));
  assert(byId('foreign-batch-time').textContent.includes(scenario==='pending'?'około 9.50 s':'bieżąca jednostka trwa dłużej'));
  await start();assert.equal(calls.length,count,'Double click must not start another batch');
  release();
 }
 if(scenario==='refresh_pending'){
  assert(releaseRefresh);const count=calls.length;await start();assert.equal(calls.length,count);
  releaseRefresh();
 }
 await work;
 const posts=calls.filter(([,o])=>o.method==='POST');
 assert.equal(calls.filter(([url,o])=>!o.method&&url.startsWith('/crm/offers/export-packages?')).length,1,'Exactly one final table refresh');
 assert.equal(byId('foreign-batch-start').disabled,false);assert.equal(cleared,1);
 if(['bad_plan','duplicate_plan','empty'].includes(scenario)){
  assert.equal(posts.length,1);assert.equal(byId('foreign-batch-results').children.length,0);
  assert.equal(value('Potwierdzone'),0);return;
 }
 if(['stop','restart'].includes(scenario)){
  assert.equal(posts.length,2);assert.equal(byId('foreign-batch-results').children.length,1);
  if(scenario==='restart'){
   assert.equal(value('Potwierdzone'),0);assert.equal(value('Niepotwierdzone'),1);
   await start();assert.equal(value('Potwierdzone'),7);assert.equal(value('Niepotwierdzone'),1);
   assert.equal(cleared,2);
  }
  return;
 }
 assert.equal(posts.length,9,'One plan and exactly one POST per unit, no automatic retries');
 const unknown=['timeout','malformed','mismatch','gateway','blocked_success'].includes(scenario)?2:1;
 assert.equal(value('Potwierdzone'),8-unknown);assert.equal(value('Niepotwierdzone'),unknown);
 for(const label of ['Zweryfikowano istniejącą','Pominięto aktualną','Bez wymaganej operacji',
  'Zablokowano','Wymaga interwencji','Błąd wykonania'])assert.equal(value(label),label==='Błąd wykonania'&&scenario==='rejected'?2:1,label);
 assert.equal(value('Przygotowano i zweryfikowano'),unknown===1&&scenario!=='rejected'?1:0);
 const rows=byId('foreign-batch-results').children;assert.equal(rows.length,8,'One row per unit');
 const text=rows[0].textContent;
 assert(text.includes('Projekt Cyprus #7'));assert(text.includes('11, 13, 15'));assert(text.includes('11, 15'));
 assert.equal(rows.filter(r=>r.textContent.includes('Projekt Cyprus #7')).length,1);
 assert(text.includes('nie należy ich sumować'));
 if(scenario==='bad_timing')assert(rows[0].textContent.includes('brak pomiaru'));
 else if(unknown===1&&scenario!=='rejected')assert(text.includes('0.70 s')&&text.includes('0.50 s'));
 assert(rows[7].textContent.includes('Nie ponowiono żądania'));
 if(scenario!=='clock_failure')assert(byId('foreign-batch-refresh').textContent.includes('1.20 s'));
 if(scenario==='refresh_failure')assert(byId('foreign-batch-refresh').textContent.includes('błąd odświeżenia'));
 byId('foreign-batch-sort').value='slowest';byId('foreign-batch-sort').listeners.change();
 if(scenario!=='clock_failure')assert(byId('foreign-batch-results').children[0].textContent.includes(scenario==='long_request'?'#103':'#107'));
 assert(byId('foreign-batch-message').textContent.includes('Nie wysłano paczek'));
})().catch(e=>{console.error(e);process.exitCode=1});
"""
    result = subprocess.run([executable, '-e', script, str(source), scenario],
                            capture_output=True, text=True, encoding='utf8', timeout=20)
    assert result.returncode == 0, result.stderr
