from pathlib import Path
import shutil
import subprocess

import pytest


ROOT = Path(__file__).resolve().parents[2]


def login(client, level='master'):
    with client.session_transaction() as session:
        session['user_id'] = 1
        session['access_level'] = level


@pytest.mark.parametrize('url', ['/crm/dashboard?panel=dbshell', '/crm/dbshell-ui',
                                 '/crm/dashboard?panel=scheduled-jobs'])
def test_single_master_administration_panel(client, tmp_path, monkeypatch, url):
    monkeypatch.setenv('DATA_DIR', str(tmp_path))
    login(client)
    page = client.get(url)
    assert page.status_code == 200
    text = page.text
    assert text.count('data-panel="dbshell"') == 1
    assert 'data-panel="scheduled-jobs"' not in text
    assert 'id="panel-scheduled-jobs"' not in text
    assert text.count('id="administration"') == 1
    assert text.count('id="scheduler-form"') == 1
    assert text.count('data-scheduler-diagnostics') == 1
    assert text.count('id="dbshell-lock-box"') == 1
    assert 'Administracja' in text
    for name in ('schedule', 'history', 'database'):
        assert text.count(f'data-admin-section="{name}"') == 1
    assert not (tmp_path / 'scheduler').exists()


@pytest.mark.parametrize('level', ['agent', 'admin'])
def test_admin_panel_is_not_available_to_non_master(client, level):
    login(client, level)
    assert client.get('/crm/dashboard?panel=dbshell').status_code == 403
    assert client.get('/crm/dashboard?panel=scheduled-jobs').status_code == 403
    assert 'id="administration"' not in client.get('/crm/dashboard').text
    assert 'data-panel="dbshell"' not in client.get('/crm/dashboard').text
    assert client.get('/crm/scheduled-jobs').status_code == 403
    assert client.get('/crm/scheduled-jobs/history').status_code == 403


def test_administration_components_have_square_corners():
    for name in ('administration.html', 'scheduled_jobs.html', 'scheduler_diagnostics.html', 'db_shell.html'):
        text = (ROOT / 'InvestmentManager/templates/investmentmanager/components' / name).read_text(encoding='utf-8-sig')
        assert 'rounded' not in text
    for name in ('db_shell.js', 'scheduler_diagnostics.js'):
        assert 'rounded' not in (ROOT / 'InvestmentManager/static/js' / name).read_text(encoding='utf-8-sig')


@pytest.mark.skipif(not shutil.which('node'), reason='Node required for JS regression')
def test_single_initialization_lazy_sections_and_manual_refresh():
    script = r'''
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
class Element {
 constructor(){this.dataset={};this.listeners={};this.children=[];this.textContent='';this.value='5';this.checked=false;this.open=false;this.classList={toggle(){},contains:()=>false};}
 addEventListener(n,f){(this.listeners[n]??=[]).push(f);}emit(n,e={}){for(const f of this.listeners[n]||[])f(e);}
 setAttribute(){} removeAttribute(){}hasAttribute(){return false;}replaceChildren(){this.children=[];}append(...nodes){this.children.push(...nodes);}
}
const els={},events={},historyDetails=new Element(),databaseDetails=new Element(),diag=new Element();
for(const id of ['scheduler-form','scheduler-enabled','scheduler-interval','scheduler-save','scheduler-refresh','scheduler-message','scheduler-status','scheduler-stats',
 'dbshell-lock-box','dbshell-main','dbshell-lock-msg','dbshell-tab-table','dbshell-tab-orphans','dbshell-tab-panel-table','dbshell-tab-panel-orphans'])els[id]=new Element();
const parts=Object.fromEntries(['refresh','message','summary','runs','issues','details','log'].map(k=>[k,new Element()]));
diag.querySelector=q=>parts[q.match(/data-role="([^"]+)"/)[1]];
diag.closest=q=>q==='[data-admin-section]'?historyDetails:{id:'panel-dbshell',classList:{contains:()=>false},hasAttribute:()=>false};
els['dbshell-lock-box'].closest=()=>databaseDetails;
global.document={getElementById:id=>els[id],querySelectorAll:()=>[diag],createElement:()=>new Element(),addEventListener:(n,f)=>(events[n]??=[]).push(f)};
global.window={};global.alert=()=>{};
const payload={config:{resize_images:{enabled:false,interval_minutes:5}},state:null,csrf_token:'test',runs:[],warnings:[],retention:30};
let calls=[];
global.fetch=async(url,options={})=>{
 calls.push({url,options});
 assert.ok(['/crm/scheduled-jobs','/crm/scheduled-jobs/history','/crm/dbshell/status'].includes(url));
 return {ok:true,json:async()=>url==='/crm/dbshell/status'?{is_master:true,unlocked:false}:payload};
};
const sources=process.argv.slice(1).map(p=>fs.readFileSync(p,'utf8'));
const flush=async()=>{for(let i=0;i<6;i++)await new Promise(setImmediate);};
const emit=(name,e)=>{for(const f of events[name]||[])f(e);};
const count=url=>calls.filter(c=>c.url===url).length;
(async()=>{
 sources.forEach(s=>vm.runInThisContext(s));await flush();
 assert.equal(calls.length,1);assert.equal(count('/crm/scheduled-jobs'),1);
 const counts=Object.fromEntries(Object.entries(events).map(([k,v])=>[k,v.length]));
 sources.forEach(s=>vm.runInThisContext(s));await flush();
 assert.deepEqual(Object.fromEntries(Object.entries(events).map(([k,v])=>[k,v.length])),counts);assert.equal(calls.length,1);
 emit('panel:shown',{detail:{panelId:'dbshell'}});emit('DOMContentLoaded',{});await flush();assert.equal(calls.length,1);
 historyDetails.open=true;historyDetails.emit('toggle');historyDetails.emit('toggle');emit('panel:shown',{detail:{panelId:'dbshell'}});
 await flush();assert.equal(count('/crm/scheduled-jobs/history'),1);
 historyDetails.open=false;historyDetails.emit('toggle');historyDetails.open=true;historyDetails.emit('toggle');await flush();assert.equal(count('/crm/scheduled-jobs/history'),1);
 databaseDetails.open=true;databaseDetails.emit('toggle');databaseDetails.emit('toggle');emit('panel:shown',{detail:{panelId:'dbshell'}});
 await flush();assert.equal(count('/crm/dbshell/status'),1);
 databaseDetails.open=false;databaseDetails.emit('toggle');databaseDetails.open=true;databaseDetails.emit('toggle');emit('panel:shown',{detail:{panelId:'dbshell'}});
 await flush();assert.equal(count('/crm/dbshell/status'),1);assert.equal(calls.length,3);
 assert.equal(calls.filter(c=>c.options.method==='POST').length,0);
 els['scheduler-enabled'].checked=true;els['scheduler-interval'].value='10';
 els['scheduler-form'].emit('submit',{preventDefault(){}});els['scheduler-form'].emit('submit',{preventDefault(){}});
 await flush();assert.equal(calls.filter(c=>c.options.method==='POST').length,1);
 assert.deepEqual(JSON.parse(calls.find(c=>c.options.method==='POST').options.body),{enabled:true,interval_minutes:10});
 parts.refresh.emit('click');await flush();assert.equal(count('/crm/scheduled-jobs/history'),2);
 assert.equal(count('/crm/dbshell/status'),1);assert.equal(count('/crm/scheduled-jobs'),2);
})().catch(e=>{console.error(e);process.exitCode=1;});
'''
    sources = [str(ROOT / 'InvestmentManager/static/js' / name)
               for name in ('scheduled_jobs.js', 'scheduler_diagnostics.js', 'db_shell.js')]
    result = subprocess.run(['node', '-e', script, *sources], capture_output=True, text=True,
                            encoding='utf-8', timeout=20)
    assert result.returncode == 0, result.stdout + result.stderr
