"""S2: agent calendar (knowledge_center/schedules/<user_id>.json) and the backup files of notes/calendars."""
import json
import os
import threading
import time

import pytest

from modules.core import storage_paths
from tests.investmentmanager.conftest import CRM_ANN, CRM_BOB

pytestmark = pytest.mark.crm_session_guard


def _file(user=CRM_ANN):
    return storage_paths.schedules_dir() / f'{user}.json'


def _events(user=CRM_ANN):
    return json.loads(_file(user).read_text(encoding='utf-8'))


def _add(client, title):
    return client.post('/crm/agent_panel/add_event', json={'title': title, 'start': '2030-01-01'})


def _own(client):
    return [e for e in client.get('/crm/agent_panel/events').get_json()]


def test_concurrent_events_from_several_devices_lose_nothing(app, crm_env, crm_login):
    devices = [crm_login(app, CRM_ANN) for _ in range(6)]
    codes = []

    def work(index, client):
        for i in range(5):
            codes.append(_add(client, f'e-{index}-{i}').status_code)

    threads = [threading.Thread(target=work, args=(i, c)) for i, c in enumerate(devices)]
    [t.start() for t in threads]
    [t.join(120) for t in threads]
    assert set(codes) == {200}
    assert {e['title'] for e in _events()} == {f'e-{i}-{j}' for i in range(6) for j in range(5)}


def test_delete_and_stale_update_never_resurrect_an_event(app, crm_env, crm_login):
    for _ in range(4):
        one, two = crm_login(app, CRM_ANN), crm_login(app, CRM_ANN)
        event = _add(one, 'visit').get_json()['event']
        results = {}
        threads = [threading.Thread(target=lambda: results.__setitem__('d', one.post('/crm/agent_panel/delete_event', json={'id': event['id']}).status_code)),
                   threading.Thread(target=lambda: results.__setitem__('u', two.post('/crm/agent_panel/update_event', json={'id': event['id'], 'title': 'changed'}).status_code))]
        [t.start() for t in threads]
        [t.join(60) for t in threads]
        assert results['d'] == 200 and results['u'] in (200, 404)
        assert _events() == []
        _file().unlink()


def test_responses_and_per_user_files_are_unchanged(app, crm_env, crm_login):
    ann, bob = crm_login(app, CRM_ANN), crm_login(app, CRM_BOB)
    created = _add(ann, 'visit').get_json()
    assert created['message'] == 'Wydarzenie zapisane' and created['event']['id'].startswith('evt_')
    event_id = created['event']['id']
    assert ann.post('/crm/agent_panel/update_event', json={'id': event_id, 'title': 'moved'}).get_json() == {'message': 'Wydarzenie zaktualizowane'}
    assert [e['title'] for e in _own(ann)] == ['moved'] and _own(bob) == []
    assert ann.post('/crm/agent_panel/update_event', json={}).status_code == 400
    assert ann.post('/crm/agent_panel/update_event', json={'id': 'nope'}).status_code == 404
    assert ann.post('/crm/agent_panel/delete_event', json={}).status_code == 400
    assert ann.post('/crm/agent_panel/delete_event', json={'id': 'nope'}).status_code == 404
    assert ann.post('/crm/agent_panel/delete_event', json={'id': event_id}).get_json() == {'message': 'Wydarzenie usunięte'}
    assert _own(ann) == []
    # a user without a file: the historic messages
    assert bob.post('/crm/agent_panel/delete_event', json={'id': 'x'}).get_json() == {'error': 'Brak pliku harmonogramu'}
    assert bob.post('/crm/agent_panel/update_event', json={'id': 'x'}).get_json() == {'error': 'Brak pliku harmonogramu'}
    assert not _file(CRM_BOB).exists()


def test_not_found_requests_do_not_rewrite_or_back_up(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    _add(ann, 'visit')
    before = os.stat(_file())
    backups = list((storage_paths.schedules_backups_dir() / str(CRM_ANN)).glob('*')) if (storage_paths.schedules_backups_dir() / str(CRM_ANN)).exists() else []
    time.sleep(0.02)
    assert ann.post('/crm/agent_panel/update_event', json={'id': 'nope'}).status_code == 404
    assert ann.post('/crm/agent_panel/delete_event', json={'id': 'nope'}).status_code == 404
    after = os.stat(_file())
    assert (before.st_ino, before.st_mtime_ns) == (after.st_ino, after.st_mtime_ns)
    assert list((storage_paths.schedules_backups_dir() / str(CRM_ANN)).glob('*')) == backups if backups else True


def test_damaged_calendar_fails_closed_for_read_and_write(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    _file().parent.mkdir(parents=True, exist_ok=True)
    damaged = b'[{"id": "evt_1", "title": "half'
    _file().write_bytes(damaged)
    for call in (lambda: ann.get('/crm/agent_panel/events'), lambda: _add(ann, 'new'),
                 lambda: ann.post('/crm/agent_panel/update_event', json={'id': 'evt_1'}),
                 lambda: ann.post('/crm/agent_panel/delete_event', json={'id': 'evt_1'})):
        response = call()
        assert response.status_code == 503 and response.get_json()['code'] == 'json_store_corrupt', response.get_data(as_text=True)
    assert _file().read_bytes() == damaged
    assert len([p for p in _file().parent.iterdir() if '.corrupt-' in p.name]) == 1


# ------------------------------------------------------------------------------------------------ backups (J7)
def test_quick_calendar_saves_keep_distinct_backups_up_to_the_limit(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    for i in range(8):
        _add(ann, f'e{i}')
    names = [p.name for p in (storage_paths.schedules_backups_dir() / str(CRM_ANN)).glob('backup_*.json')]
    assert len(names) == 5 == len(set(names))            # before: one file per minute, so quick saves overwrote each other


def test_quick_note_saves_keep_distinct_backups_up_to_the_limit(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    for i in range(13):
        ann.post('/crm/knowledge/add_note', json={'title': f'n{i}', 'content': 'c', 'is_private': True})
    names = [p.name for p in storage_paths.knowledge_center_backups_dir().glob('all_notes_backup_*.json')]
    assert len(names) == 10 == len(set(names))           # before: one file per second
    newest = sorted(names)[-1]
    assert len(json.loads((storage_paths.knowledge_center_backups_dir() / newest).read_text(encoding='utf-8'))) == 12   # state before the 13th save


def test_old_style_backup_names_still_rotate_correctly(app, crm_env, crm_login):
    folder = storage_paths.schedules_backups_dir() / str(CRM_ANN)
    folder.mkdir(parents=True)
    for i in range(7):
        (folder / f'backup_2026010{i}_0000.json').write_text('[]')
    ann = crm_login(app, CRM_ANN)
    _add(ann, 'one')
    _add(ann, 'two')
    remaining = sorted(p.name for p in folder.glob('backup_*.json'))
    # the 1st add creates no backup (no file yet), the 2nd adds one new-style backup: 8 files -> the 3 oldest OLD ones are trimmed
    assert len(remaining) == 5 and remaining[-1].count('_') == 3 and remaining[-1] > remaining[-2]
    assert not {'backup_20260100_0000.json', 'backup_20260101_0000.json', 'backup_20260102_0000.json'} & set(remaining)
