from contextlib import contextmanager
import json
import os
from pathlib import Path
import shutil
import subprocess

import pytest

from InvestmentManager import scheduled_jobs as jobs


@pytest.fixture
def runtime(tmp_path, monkeypatch):
    monkeypatch.setenv('DATA_DIR', str(tmp_path))
    (tmp_path / 'offers').mkdir()
    return tmp_path


@pytest.fixture
def worker(runtime, monkeypatch):
    from tools import resize_images

    @contextmanager
    def lock(path):
        yield True

    def run():
        print('Offers root: C:/private/data')
        print('Successfully resized: /home/private/image.jpg (new size: 400x300)')
        print('Unsafe image conversion skipped: password=HIDDEN_SECRET')
        print('Failed to process /home/private/image.jpg: token=HIDDEN_SECRET')
        print('Traceback (most recent call last): HIDDEN_SECRET')
        print('Summary: offers=2, conversions=0, conversion_skips=1, resizes=1, thumbnails=1, thumbnail_skips=0, missing_thumbnail_sources=0, errors=1')
        return {'errors': 1, 'offers_scanned': 2, 'resizes': 1}

    monkeypatch.setattr(resize_images, 'process_lock', lock)
    monkeypatch.setattr(resize_images, 'run', run)
    jobs.configure({'version': 1, 'resize_images': {'enabled': True, 'interval_minutes': 5}}, now=0)
    return resize_images


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


def test_actual_events_shared_history_safe_and_no_read_effects(worker, runtime, client, monkeypatch):
    result = jobs.tick(now=300)
    run_id = result['attempt']['id']
    assert result['diagnostics_saved'] is True
    archive = runtime / 'scheduler/runs' / (run_id + '.json')
    original = archive.read_bytes()
    private = (runtime / 'scheduler/scheduler.log').read_text(encoding='utf-8')
    assert 'HIDDEN_SECRET' in private  # Raw private log is never served.
    assert b'HIDDEN_SECRET' not in original
    login(client)
    before = {str(p): p.read_bytes() for p in (runtime / 'scheduler').rglob('*') if p.is_file()}
    monkeypatch.setattr(jobs, 'runner_lock', lambda: pytest.fail('No diagnostic locks'))
    monkeypatch.setattr(worker, 'run', lambda: pytest.fail('No diagnostic jobs'))
    history = client.get('/crm/scheduled-jobs/history')
    detail = client.get('/crm/scheduled-jobs/history/' + run_id)
    assert history.status_code == detail.status_code == 200
    assert len(history.json['runs']) == 1
    assert history.json['runs'][0]['attempt'] == detail.json['attempt'] == result['attempt']
    assert {e['level'] for e in detail.json['events']} >= {'warning', 'error', 'info'}
    assert any(e['message'].startswith('Summary: offers=2') for e in detail.json['events'])
    assert any(e['message'] == 'resize_images result=error' for e in detail.json['events'])
    for response in (history, detail):
        assert response.cache_control.no_store
        for secret in ('HIDDEN_SECRET', '/home/private', 'C:/private', 'Traceback'):
            assert secret not in response.text
    assert {str(p): p.read_bytes() for p in (runtime / 'scheduler').rglob('*') if p.is_file()} == before


@pytest.mark.parametrize('role', [None, 'agent', 'admin'])
@pytest.mark.parametrize('suffix', ['', '/' + 'a' * 32])
def test_auth(client, runtime, role, suffix):
    if role:
        login(client, role)
    assert client.get('/crm/scheduled-jobs/history' + suffix).status_code == 403
    assert not (runtime / 'scheduler').exists()


def test_master_diagnostics_does_not_unlock_database(client, runtime):
    login(client)
    assert client.get('/crm/scheduled-jobs/history').status_code == 200
    assert client.get('/crm/dbshell/status').json['unlocked'] is False
    assert client.get('/crm/dbshell/tables').status_code == 401
    page = client.get('/crm/dbshell-ui')
    assert 'Scheduler — zadania cykliczne' in page.text
    assert 'js/scheduler_diagnostics.js' in page.text
    assert not (runtime / 'scheduler').exists()


def test_history_retention_and_truncation(worker, runtime, monkeypatch):
    def noisy():
        for i in range(150):
            print('Successfully resized: secret-' + str(i))
        return {'errors': 0}

    monkeypatch.setattr(worker, 'run', noisy)
    for i in range(jobs.HISTORY_LIMIT + 2):
        assert jobs.tick(now=300 * (i + 1))['outcome'] == 'success'
    files = list((runtime / 'scheduler/runs').glob('*.json'))
    assert len(files) == jobs.HISTORY_LIMIT
    history = jobs.diagnostics()
    assert len(history['runs']) == jobs.HISTORY_LIMIT
    assert history['runs'][0]['attempt']['started_at'] == 300 * (jobs.HISTORY_LIMIT + 2)
    assert min(row['attempt']['started_at'] for row in history['runs']) == 900
    detail = jobs.diagnostics(history['runs'][0]['attempt']['id'])
    assert detail['truncated'] and len(detail['events']) == jobs.EVENT_LIMIT
    assert max(file.stat().st_size for file in files) <= 65536


@pytest.mark.parametrize('raw', ['{broken', '[]', 'x' * 65537], ids=['json', 'type', 'size'])
def test_corrupt_record_is_explicit_and_not_modified(worker, runtime, client, raw):
    run_id = jobs.tick(now=300)['attempt']['id']
    path = runtime / 'scheduler/runs' / (run_id + '.json')
    path.write_text(raw)
    login(client)
    response = client.get('/crm/scheduled-jobs/history')
    assert response.status_code == 200
    assert response.json['warnings']
    assert response.json['runs'][0]['log_available'] is False
    assert client.get('/crm/scheduled-jobs/history/' + run_id).status_code == 409
    assert path.read_text() == raw


def test_untrusted_stored_message_resanitized(worker, runtime, client):
    run_id = jobs.tick(now=300)['attempt']['id']
    path = runtime / 'scheduler/runs' / (run_id + '.json')
    record = json.loads(path.read_text())
    record['events'][0]['message'] = 'secret=SHOULD_NOT_LEAK /home/private'
    path.write_text(json.dumps(record))
    login(client)
    assert 'SHOULD_NOT_LEAK' not in client.get('/crm/scheduled-jobs/history/' + run_id).text


def test_history_failure_does_not_change_result(worker, monkeypatch):
    original = jobs._write

    def fail_archive(name, value):
        if name.startswith('runs/'):
            raise OSError('private disk error')
        return original(name, value)

    monkeypatch.setattr(jobs, '_write', fail_archive)
    result = jobs.tick(now=300)
    assert result['outcome'] == 'error'  # Same actual image error, not a scheduler/history failure.
    assert result['diagnostics_saved'] is False
    assert jobs.status()['state']['attempt'] == result['attempt']
    assert jobs.diagnostics()['warnings']


def test_interrupted_run_record_preserves_actual_events(worker, monkeypatch):
    def fail():
        print('Failed to process /private/file: secret')
        raise KeyboardInterrupt()

    monkeypatch.setattr(worker, 'run', fail)
    with pytest.raises(KeyboardInterrupt):
        jobs.tick(now=300)
    run_id = jobs.status()['state']['attempt']['id']
    assert jobs.diagnostics(run_id)['attempt']['outcome'] == 'running'
    assert jobs.tick(now=301)['outcome'] == 'interrupted'
    detail = jobs.diagnostics(run_id)
    assert detail['attempt']['outcome'] == 'interrupted'
    assert any(event['level'] == 'error' for event in detail['events'])


def test_reads_while_runner_busy(worker):
    run_id = jobs.tick(now=300)['attempt']['id']
    with jobs.runner_lock() as locked:
        assert locked
        assert jobs.diagnostics()['runs']
        assert jobs.diagnostics(run_id)['attempt']['id'] == run_id


@pytest.mark.parametrize('suffix,status', [('/bad-id', 400), ('/' + 'a' * 32, 404),
    ('?path=/etc/passwd', 400), ('/..%2F..%2Fconfig.json', 404)])
def test_no_arbitrary_path_access(client, runtime, suffix, status):
    login(client)
    assert client.get('/crm/scheduled-jobs/history' + suffix).status_code == status


def test_log_symlink_rejected(worker, runtime, client):
    run_id = jobs.tick(now=300)['attempt']['id']
    path = runtime / 'scheduler/runs' / (run_id + '.json')
    secret = runtime / 'secret.json'
    secret.write_text('HIDDEN_SECRET')
    path.unlink()
    try:
        path.symlink_to(secret)
    except OSError:
        pytest.skip('Symlinks unavailable on Windows')
    login(client)
    response = client.get('/crm/scheduled-jobs/history/' + run_id)
    assert response.status_code in (409, 503)
    assert 'HIDDEN_SECRET' not in response.text


def test_private_raw_log_rotates(worker, runtime, monkeypatch):
    original = jobs.RotatingFileHandler
    monkeypatch.setattr(jobs, 'RotatingFileHandler', lambda path, **kw: original(path, maxBytes=150, backupCount=3, encoding='utf-8'))
    jobs.tick(now=300)
    logs = list((runtime / 'scheduler').glob('scheduler.log*'))
    assert 1 < len(logs) <= 4


def test_absent_history_has_no_writes(runtime):
    assert jobs.diagnostics()['runs'] == []
    assert not (runtime / 'scheduler').exists()


def test_archive_size_limit_preserves_existing_record(worker, runtime):
    attempt = jobs.tick(now=300)['attempt']
    path = runtime / 'scheduler/runs' / (attempt['id'] + '.json')
    original = path.read_bytes()
    events = [{'at': 300, 'level': 'info', 'message': 'x' * 700}] * jobs.EVENT_LIMIT
    assert jobs._save_run(attempt, events) is False
    assert path.read_bytes() == original


@pytest.mark.parametrize('raw', ['[' * 1200 + '0' + ']' * 1200,
    '{"version":1,"next_due":' + '9' * 4000 + ',"last_success":null,"attempt":null}'], ids=['nested', 'huge-number'])
def test_extreme_corrupt_state_safe_response(runtime, client, raw):
    path = runtime / 'scheduler'
    path.mkdir()
    (path / 'state.json').write_text(raw)
    login(client)
    response = client.get('/crm/scheduled-jobs/history')
    assert response.status_code == 409
    assert 'Traceback' not in response.text
    assert (path / 'state.json').read_text() == raw


@pytest.mark.skipif(not shutil.which('node'), reason='Node required for frontend regression')
def test_shared_frontend_renders_history_and_reads_only_selected_log():
    script = r'''
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
class Element {
 constructor(){this.textContent='';this.children=[];this.listeners={};this.dataset={};this.disabled=false;}
 addEventListener(n,f){this.listeners[n]=f;}setAttribute(){}removeAttribute(){}
 replaceChildren(){this.children=[];}append(...nodes){this.children.push(...nodes);}
}
const roles=['refresh','message','summary','runs','issues','details','log'];
function section(name,hidden){
 const s=new Element();s.parts=Object.fromEntries(roles.map(r=>[r,new Element()]));
 s.querySelector=q=>s.parts[q.match(/data-role="([^"]+)"/)[1]];
 s.closest=q=>q==='[data-admin-section]'?null:({id:'panel-'+name,classList:{contains:()=>hidden},hasAttribute:()=>hidden});return s;
}
const a=section('dbshell',false),b=section('scheduled-jobs',true),events=[];
global.document={querySelectorAll:()=>[a,b],createElement:()=>new Element(),addEventListener:(n,f)=>events.push(f)};
const attempt={id:'a'.repeat(32),started_at:300,finished_at:302,duration_seconds:2,outcome:'success',stats:{offers_scanned:2}};
const history={config:{resize_images:{enabled:true}},state:{attempt,next_due:600,last_success:302},
 runs:[{attempt,issues:[{at:301,level:'warning',message:'safe warning'}],log_available:true}],warnings:[],retention:30};
let calls=[],release,fail=false;
global.fetch=async(url,options)=>{
 calls.push(url);assert.equal(options.method,undefined);
 if(url.endsWith('/'+attempt.id))await new Promise(resolve=>release=resolve);
 return {ok:!fail,json:async()=>fail?{error:'read failed'}:url.endsWith('/'+attempt.id)?
 {attempt,events:[{at:301,level:'info',message:'actual <text>'}],truncated:true}:history};
};
vm.runInThisContext(fs.readFileSync(process.argv[1],'utf8'));
const flush=async()=>{for(let i=0;i<6;i++)await new Promise(setImmediate);};
(async()=>{
 await flush();assert.equal(calls.length,1);assert.equal(a.parts.runs.children.length,1);assert.equal(b.parts.runs.children.length,0);
 assert.match(a.parts.issues.textContent,/safe warning/);
 const button=a.parts.runs.children[0].children[5].children[0];
 button.listeners.click();button.listeners.click();await flush();assert.equal(calls.length,2);assert.equal(button.disabled,true);
 release();await flush();assert.equal(button.disabled,false);assert.equal(a.parts.details.open,true);
 assert.match(a.parts.log.textContent,/actual <text>/);assert.match(a.parts.log.textContent,/limit wpisów/);
 events.forEach(f=>f({detail:{panelId:'scheduled-jobs'}}));await flush();assert.equal(calls.length,3);assert.equal(b.parts.runs.children.length,1);
 fail=true;a.parts.refresh.listeners.click();await flush();assert.match(a.parts.message.textContent,/wcześniejszy widok/);
 assert.equal(a.parts.runs.children.length,1);assert.equal(a.parts.refresh.disabled,false);
 assert.equal(calls.length,4);
})().catch(e=>{console.error(e);process.exitCode=1;});
'''
    source = Path(__file__).resolve().parents[2] / 'InvestmentManager/static/js/scheduler_diagnostics.js'
    result = subprocess.run(['node', '-e', script, str(source)], capture_output=True,
                            text=True, encoding='utf-8', timeout=20)
    assert result.returncode == 0, result.stdout + result.stderr
