"""S2: Knowledge Center (all_notes.json + notifications.json, shared by every agent) - locked transactions, fail closed."""
import json
import threading

import pytest

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

pytestmark = pytest.mark.crm_session_guard


def _notes_path():
    return storage_paths.knowledge_center_notes_path()


def _notifications_path():
    return storage_paths.knowledge_center_notifications_path()


def _notes():
    return json.loads(_notes_path().read_text(encoding='utf-8'))


def _notifications():
    return json.loads(_notifications_path().read_text(encoding='utf-8'))


def _add(client, title, private=True):
    return client.post('/crm/knowledge/add_note', json={'title': title, 'content': 'c', 'is_private': private})


def _backups():
    folder = storage_paths.knowledge_center_backups_dir()
    return sorted(folder.glob('all_notes_backup_*.json')) if folder.exists() else []


def test_concurrent_adds_lose_no_note(app, crm_env, crm_login):
    clients = [crm_login(app, [CRM_ANN, CRM_BOB, CRM_MASTER][i % 3]) for i in range(6)]
    codes = []

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

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


def test_author_edit_keeps_comments_added_by_a_colleague(app, crm_env, crm_login):
    """The old edit carried a stale comment list and silently dropped a colleague's comment."""
    for _ in range(4):
        ann, bob = crm_login(app, CRM_ANN), crm_login(app, CRM_BOB)
        _add(ann, 'shared', private=False)
        ts = [n for n in ann.get('/crm/knowledge/get_notes').get_json()['public'] if n['title'] == 'shared'][0]['timestamp']
        results = {}
        threads = [threading.Thread(target=lambda: results.__setitem__('c', bob.post('/crm/knowledge/add_comment', json={'note_timestamp': ts, 'comment': 'keep me'}).status_code)),
                   threading.Thread(target=lambda: results.__setitem__('e', ann.post('/crm/knowledge/add_note', json={'title': 'edited', 'content': 'x', 'is_private': False, 'edit_mode': True, 'original_timestamp': ts}).status_code))]
        [t.start() for t in threads]
        [t.join(60) for t in threads]
        note = [n for n in _notes() if n['title'] == 'edited']
        # the edit re-stamps the note, so a comment sent against the OLD timestamp after the edit is a legitimate 404;
        # what must never happen is a 200 comment that is missing from the file
        assert results['e'] == 200 and len(note) == 1
        if results['c'] == 200:
            assert [c['comment'] for c in note[0]['comments']] == ['keep me']
        else:
            assert results['c'] == 404
        _notes_path().write_text('[]', encoding='utf-8')


def test_comment_then_edit_sequence_is_deterministic(app, crm_env, crm_login):
    ann, bob = crm_login(app, CRM_ANN), crm_login(app, CRM_BOB)
    _add(ann, 'shared', private=False)
    ts = _notes()[0]['timestamp']
    assert bob.post('/crm/knowledge/add_comment', json={'note_timestamp': ts, 'comment': 'important'}).status_code == 200
    assert ann.post('/crm/knowledge/add_note', json={'title': 'edited', 'content': 'x', 'is_private': False, 'edit_mode': True, 'original_timestamp': ts}).status_code == 200
    assert [c['comment'] for c in _notes()[0]['comments']] == ['important']


def test_notifications_are_not_lost_between_mark_read_and_comment(app, crm_env, crm_login):
    for _ in range(5):
        ann, master = crm_login(app, CRM_ANN), crm_login(app, CRM_MASTER)
        bob = crm_login(app, CRM_BOB)
        _notes_path().parent.mkdir(parents=True, exist_ok=True)
        _notes_path().write_text(json.dumps([{'title': 'shared', 'content': 'c', 'timestamp': 'T1', 'author_id': CRM_BOB, 'private': False, 'comments': []}]), encoding='utf-8')
        _notifications_path().write_text(json.dumps([{'user_id': CRM_MASTER, 'type': 'new_note', 'note_id': 'old', 'title': 'old', 'timestamp': 't', 'read': False}]), encoding='utf-8')
        threads = [threading.Thread(target=lambda: master.post('/crm/knowledge/mark_notifications_read', json={'note_id': 'old', 'type': 'new_note'})),
                   threading.Thread(target=lambda: ann.post('/crm/knowledge/add_comment', json={'note_timestamp': 'T1', 'comment': 'hi'}))]
        [t.start() for t in threads]
        [t.join(60) for t in threads]
        assert sorted((n['user_id'], n['type']) for n in _notifications()) == [(CRM_MASTER, 'new_comment'), (CRM_BOB, 'new_comment')]


def test_public_note_notifies_everybody_else_once(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    assert _add(ann, 'public', private=False).status_code == 200
    assert sorted(n['user_id'] for n in _notifications()) == [CRM_MASTER, CRM_BOB]
    assert {n['type'] for n in _notifications()} == {'new_note'}


def test_backup_holds_the_state_before_the_change_and_is_skipped_when_nothing_changes(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    _add(ann, 'first')
    after_first = _notes_path().read_text(encoding='utf-8')
    _add(ann, 'second')
    backups = _backups()
    assert len(backups) >= 1 and backups[-1].read_text(encoding='utf-8') == after_first
    count = len(_backups())
    assert ann.post('/crm/knowledge/delete_note', json={'timestamp': 'does-not-exist'}).status_code == 200
    assert ann.post('/crm/knowledge/add_comment', json={'note_timestamp': 'nope', 'comment': 'x'}).status_code == 404
    assert ann.post('/crm/knowledge/add_note', json={'title': 't', 'content': 'c', 'edit_mode': True, 'original_timestamp': 'nope'}).status_code == 404
    assert len(_backups()) == count and [n['title'] for n in _notes()] == ['second', 'first']


def test_rejected_operations_do_not_create_the_file(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    assert ann.post('/crm/knowledge/add_comment', json={'note_timestamp': 'nope', 'comment': 'x'}).status_code == 404
    assert ann.post('/crm/knowledge/delete_note', json={'timestamp': 'nope'}).status_code == 200
    assert ann.post('/crm/knowledge/mark_notifications_read', json={}).status_code == 200
    assert not _notes_path().exists() and not _notifications_path().exists()


def test_exception_in_the_domain_operation_writes_nothing(app, crm_env, crm_login, monkeypatch):
    ann = crm_login(app, CRM_ANN)
    _add(ann, 'keep')
    before = _notes_path().read_bytes()
    from InvestmentManager.routes import knowledge_center as kc
    monkeypatch.setattr(kc, 'backup_notes', lambda: (_ for _ in ()).throw(RuntimeError('backup failed')))
    try:
        response = _add(ann, 'lost?')
        assert response.status_code == 500
    except RuntimeError:
        pass
    assert _notes_path().read_bytes() == before


def test_deleting_only_removes_own_notes_and_responses_are_unchanged(app, crm_env, crm_login):
    ann, bob = crm_login(app, CRM_ANN), crm_login(app, CRM_BOB)
    assert _add(ann, 'mine').get_json() == {'message': 'Notatka zapisana'}
    ts = _notes()[0]['timestamp']
    assert bob.post('/crm/knowledge/delete_note', json={'timestamp': ts}).get_json() == {'message': 'Notatka usunięta'}
    assert len(_notes()) == 1
    assert ann.post('/crm/knowledge/delete_note', json={}).status_code == 400
    assert ann.post('/crm/knowledge/delete_note', json={'timestamp': ts}).get_json() == {'message': 'Notatka usunięta'}
    assert _notes() == []


@pytest.mark.parametrize('which', ['notes', 'notifications'])
def test_damaged_store_fails_closed_and_is_never_overwritten(app, crm_env, crm_login, which):
    ann = crm_login(app, CRM_ANN)
    damaged = b'[{"title": "half'
    target = _notes_path() if which == 'notes' else _notifications_path()
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_bytes(damaged)
    # each file only affects the endpoints that really use it (the other store is healthy and keeps working)
    calls = [lambda: ann.get('/crm/knowledge/get_notes'), lambda: ann.get('/crm/knowledge/get_comments/T1'),
             lambda: ann.post('/crm/knowledge/add_comment', json={'note_timestamp': 'T1', 'comment': 'x'}),
             lambda: ann.post('/crm/knowledge/delete_note', json={'timestamp': 'T1'}), lambda: _add(ann, 'new')]
    if which == 'notifications':
        calls = [lambda: ann.get('/crm/knowledge/get_notifications'), lambda: ann.post('/crm/knowledge/mark_notifications_read', json={}),
                 lambda: ann.get('/crm/knowledge/get_notes')]          # get_notes also reads the notifications (highlights)
    else:
        healthy = ann.get('/crm/knowledge/get_notifications')
        assert healthy.status_code == 200 and healthy.get_json() == []
    for call in calls:
        response = call()
        assert response.status_code == 503 and response.get_json()['code'] == 'json_store_corrupt', response.get_data(as_text=True)
    assert target.read_bytes() == damaged
    assert len([p for p in target.parent.iterdir() if '.corrupt-' in p.name]) == 1
