"""S2: leads (manual_leads.json, one file shared by every agent) - locked transactions, fail-closed on a damaged file."""
import json
import os
import threading
import time

import pytest

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

pytestmark = pytest.mark.crm_session_guard


def _path():
    return storage_paths.knowledge_center_manual_leads_path()


def _leads(client):
    return client.get('/crm/leadhunter/get_leads').get_json()


def _add(client, name):
    return client.post('/crm/leadhunter/add_manual_lead', json={'name': name, 'phone': '500100200'})


def test_concurrent_adds_from_many_agents_lose_nothing(app, crm_env, crm_login):
    clients = [crm_login(app, CRM_ANN if i % 2 else CRM_BOB) for i in range(6)]
    errors = []

    def work(index, client):
        for i in range(5):
            response = _add(client, f'lead-{index}-{i}')
            if response.status_code != 200:
                errors.append(response.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 errors == []
    names = {lead['name'] for lead in json.loads(_path().read_text(encoding='utf-8'))}
    assert names == {f'lead-{i}-{j}' for i in range(6) for j in range(5)}


def test_delete_then_stale_update_does_not_resurrect_the_lead(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    _add(ann, 'Lead')
    lead_id = _leads(ann)[0]['id']
    assert ann.post('/crm/leadhunter/delete_lead', json={'id': lead_id}).status_code == 200
    response = ann.post('/crm/leadhunter/update_lead', json={'id': lead_id, 'phone': '999'})
    assert response.status_code == 404
    assert json.loads(_path().read_text(encoding='utf-8')) == []


def test_concurrent_delete_and_update_never_leave_a_resurrected_lead(app, crm_env, crm_login):
    """Both orders are legal; the only wrong end state is 'deleted but present with the update applied' - impossible now
    because the second transaction reads the first one's result."""
    for _ in range(5):
        ann1, ann2 = crm_login(app, CRM_ANN), crm_login(app, CRM_ANN)
        _add(ann1, 'Lead')
        lead_id = _leads(ann1)[0]['id']
        results = {}
        threads = [threading.Thread(target=lambda: results.__setitem__('d', ann1.post('/crm/leadhunter/delete_lead', json={'id': lead_id}).status_code)),
                   threading.Thread(target=lambda: results.__setitem__('u', ann2.post('/crm/leadhunter/update_lead', json={'id': lead_id, 'phone': '999'}).status_code))]
        [t.start() for t in threads]
        [t.join(60) for t in threads]
        assert results['d'] == 200
        assert json.loads(_path().read_text(encoding='utf-8')) == []          # delete always wins over a later/parallel update
        assert results['u'] in (200, 404)


def test_responses_and_rules_are_unchanged(app, crm_env, crm_login):
    ann, bob = crm_login(app, CRM_ANN), crm_login(app, CRM_BOB)
    assert _add(ann, 'Lead').get_json() == {'message': 'Lead zapisany pomyślnie'}
    lead_id = _leads(ann)[0]['id']
    assert bob.post('/crm/leadhunter/update_lead', json={'id': lead_id, 'name': 'x'}).status_code == 403
    assert bob.post('/crm/leadhunter/delete_lead', json={'id': lead_id}).status_code == 403
    assert ann.post('/crm/leadhunter/update_lead', json={'id': lead_id, 'name': 'New'}).get_json() == {'message': 'Lead zaktualizowany'}
    assert ann.post('/crm/leadhunter/update_lead', json={'id': 'nope', 'name': 'x'}).status_code == 404
    assert ann.post('/crm/leadhunter/delete_lead', json={}).status_code == 400
    assert ann.get(f'/crm/leadhunter/get_lead?id={lead_id}').get_json()['name'] == 'New'
    assert ann.post('/crm/leadhunter/delete_lead', json={'id': lead_id}).get_json() == {'message': 'Lead usunięty'}


def test_missing_file_is_an_empty_list_and_rejected_requests_create_no_file(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    assert _leads(ann) == [] and not _path().exists()
    assert ann.post('/crm/leadhunter/delete_lead', json={'id': 'nope'}).status_code == 404
    assert _add(ann, '').status_code == 400
    assert not _path().exists()


def test_forbidden_update_does_not_rewrite_the_file(app, crm_env, crm_login):
    ann, bob = crm_login(app, CRM_ANN), crm_login(app, CRM_BOB)
    _add(ann, 'Lead')
    lead_id = _leads(ann)[0]['id']
    before = os.stat(_path())
    time.sleep(0.02)
    assert bob.post('/crm/leadhunter/update_lead', json={'id': lead_id, 'name': 'x'}).status_code == 403
    after = os.stat(_path())
    assert (before.st_ino, before.st_mtime_ns) == (after.st_ino, after.st_mtime_ns)


@pytest.mark.parametrize('damaged', [b'', b'[{"id": "1", "na', b'{}'])
def test_damaged_store_fails_closed_everywhere_and_is_never_overwritten(app, crm_env, crm_login, damaged):
    ann = crm_login(app, CRM_ANN)
    _path().parent.mkdir(parents=True, exist_ok=True)
    _path().write_bytes(damaged)
    calls = [lambda: ann.get('/crm/leadhunter/get_leads'), lambda: ann.get('/crm/leadhunter/get_lead?id=1'),
             lambda: ann.post('/crm/leadhunter/reverse_match_leads', json={'estate': {'Miejscowosc': 'x'}}),
             lambda: _add(ann, 'New lead'), lambda: ann.post('/crm/leadhunter/update_lead', json={'id': '1', 'name': 'x'}),
             lambda: ann.post('/crm/leadhunter/delete_lead', json={'id': '1'})]
    for call in calls:
        response = call()
        body = response.get_json()
        assert response.status_code == 503 and body['code'] == 'json_store_corrupt' and body['request_id']
    assert _path().read_bytes() == damaged                                    # the damaged file is exactly as it was
    copies = [p for p in _path().parent.iterdir() if '.corrupt-' in p.name]
    assert len(copies) == 1 and copies[0].read_bytes() == damaged             # one idempotent diagnostic copy


def test_busy_store_is_a_controlled_503_with_retry_after(app, crm_env, crm_login, monkeypatch):
    ann = crm_login(app, CRM_ANN)
    monkeypatch.setattr(json_store, 'LOCK_TIMEOUT_SECONDS', 0.3)
    holding, release = threading.Event(), threading.Event()

    def holder():
        with json_store.locked_json(str(_path()), list) as data:
            holding.set()
            release.wait(10)

    thread = threading.Thread(target=holder)
    thread.start()
    holding.wait(10)
    response = _add(ann, 'Blocked')
    release.set()
    thread.join(10)
    assert response.status_code == 503 and response.get_json()['code'] == 'json_store_busy'
    assert response.headers['Retry-After'] == '2'
    assert _add(ann, 'Now ok').status_code == 200
