"""Downloads require a click and explicit consent for diagnostic STALE bytes."""
import json
import shutil
import subprocess

import pytest

from tests.investmentmanager.test_export_package_panel import HARNESS, JS


@pytest.mark.parametrize('mode', ['ready', 'manifest', 'stale', 'became_stale', 'cancel', 'invalid', 'failure', 'network', 'no_click'])
def test_download_ui(mode):
    node = shutil.which('node')
    if not node:
        pytest.skip('Node unavailable')
    setup = HARNESS[:HARNESS.index('(async()=>{')]
    script = setup + r'''
const assert=require('node:assert/strict'),mode=process.argv[3];
els['packages-domain'].value='foreign';let confirmations=0,binary=0;
window.confirm=()=>{confirmations++;return mode!=='cancel'};
const downloads=[];Element.prototype.click=function(){downloads.push({name:this.download,href:this.href})};
URL.createObjectURL=()=> 'blob:synthetic';URL.revokeObjectURL=()=>{};
const packageState=['stale','cancel'].includes(mode)?'STALE':mode==='invalid'?'INVALID':'READY';
const foreign={...row,domain:'foreign',state:packageState,checked_at:'2026-10-25T10:01:00Z',subject:{kind:'cyprus_development',id:7},members:[11,13]};
global.fetch=async(url,options={})=>{
 calls.push({url,options});
 if(url.includes('/download?')){
  binary++;assert(!options.method||options.method==='GET');
  if(mode==='network')throw Error('NETWORK_LOST');
  if(mode==='failure')return {ok:false,status:409,json:async()=>({state:'INVALID',error:'CORRUPT'})};
  if(mode==='became_stale'&&!url.includes('diagnostic=1'))return {ok:false,status:409,json:async()=>({state:'STALE',diagnostic_available:true})};
  if(['stale','became_stale'].includes(mode))assert(url.includes('diagnostic=1'));
  return {ok:true,headers:{get:name=>name==='content-type'?'application/zip':(['stale','became_stale'].includes(mode)?'STALE':'READY')},blob:async()=>({})};
 }
 assert(url.startsWith('/crm/offers/export-packages?'));
 return {ok:true,json:async()=>({items:[foreign],total:1,notice:'metadata'})};
};
(async()=>{
 events['panel:shown']({detail:{panelId:'export-packages'}});await flush();
 assert.equal(binary,0);assert.equal(downloads.length,0);
 if(mode==='no_click')return;
 let button=packageRows()[0].children[4].children[1];
 if(mode==='manifest'){
  packageRows()[0].children[4].children[0].listeners.click();await flush();
  button=els['packages-details'].children.find(e=>e.tag==='button'&&e.textContent.includes('manifest'));
 }
 const first=button.listeners.click();await button.listeners.click();await first;await flush();
 if(['cancel','invalid'].includes(mode)){assert.equal(binary,0);assert.equal(downloads.length,0);return;}
 assert.equal(binary,mode==='became_stale'?2:1);
 if(['failure','network'].includes(mode)){assert.equal(downloads.length,0);return;}
 assert.equal(downloads.length,1);assert.equal(confirmations,['stale','became_stale'].includes(mode)?1:0);
 assert.equal(downloads[0].name.startsWith('DIAGNOSTIC_STALE_'),['stale','became_stale'].includes(mode));
 if(mode==='manifest')assert(calls.some(c=>c.url.includes('artifact=manifest')));
 assert(!calls.some(c=>c.options.method==='POST'));
 assert(!calls.some(c=>/prepare|attempt|transport|ack/.test(c.url.replace('export-packages',''))));
})().catch(e=>{console.error(e);process.exit(1)});
'''
    result = subprocess.run([node, '-e', script, str(JS), json.dumps({'count': 3, 'fail': False}), mode],
                            capture_output=True, text=True, encoding='utf8', timeout=15)
    assert result.returncode == 0, result.stderr
