"""S3 / E1-E7: unexpected exceptions are not shown to the client (generic message + request_id), the details stay in the server log,
and deliberate validation / domain errors keep their own messages and status codes."""
import contextlib
import logging

import pytest

from tests.investmentmanager.conftest import CRM_ANN, CRM_MASTER

pytestmark = pytest.mark.crm_session_guard
SECRET = 'sqlite3.OperationalError: no such table: secret_tbl (/home/user/InvestmentData/platform_logs.db)'
LEAD_FORM = {'phone': '500100200', 'offer_id': '7', 'submission_id': '5ae6ca25-bf66-4654-8b4c-c952d41edab1'}


def _boom(*args, **kwargs):
    raise RuntimeError(SECRET)


def _assert_logged(caplog, context_fragment):
    messages = [r.getMessage() for r in caplog.records if r.levelno >= logging.ERROR]
    assert any(SECRET in m and 'request_id=' in m and context_fragment in m for m in messages), messages
    return messages


def _assert_clean(response, *, status, request_id=True):
    body = response.get_data(as_text=True)
    assert response.status_code == status and SECRET not in body and 'secret_tbl' not in body and '/home/' not in body
    if request_id:
        assert response.get_json()['request_id']


# ------------------------------------------------------------------------------------------------ public site (anonymous)
def test_e1_send_lead_returns_a_generic_error(app, monkeypatch, caplog):
    from InvestmentWebsite.blueprints.investment import investment as module
    monkeypatch.setattr(module, 'send_investment_lead', _boom)
    monkeypatch.setattr(module, '_public_form_verified', lambda fields: True)
    response = app.test_client().post('/send-lead', data=LEAD_FORM)
    _assert_clean(response, status=500, request_id=False)
    assert response.get_json() == {'success': False, 'error': 'Server error.'}
    assert 'send_lead failed [request_id=' in caplog.text
    assert SECRET not in caplog.text


def test_e1_send_lead_success_path_is_unchanged(app, monkeypatch):
    from InvestmentWebsite.blueprints.investment import investment as module
    monkeypatch.setattr(module, 'send_investment_lead', lambda **kw: ({'success': True}, 200))
    monkeypatch.setattr(module, '_public_form_verified', lambda fields: True)
    assert app.test_client().post('/send-lead', data=LEAD_FORM).get_json() == {'success': True}


def test_e2_offer_page_failure_renders_the_site_500_page_without_the_exception(app, monkeypatch, caplog):
    from InvestmentWebsite.blueprints.investment import investment as module
    view = {'offer': {'id': 7}, 'video_exists': False, 'detail_items': [], 'gallery_images': [], 'canonical_slug': '7', 'canonical_path': '/nieruchomosc/7',
            'canonical_url': 'http://localhost/nieruchomosc/7',
            'offer_meta': {'page_title': 't', 'meta_description': 'd', 'og_image': '', 'breadcrumb_schema': {}, 'offer_schema': {}}}
    monkeypatch.setattr(module.investment_facade, 'build_offer_page_view', lambda **kw: (view, None))
    monkeypatch.setattr(module, 'cacheable_response', _boom)
    response = app.test_client().get('/nieruchomosc/7')
    assert response.status_code == 500 and SECRET not in response.get_data(as_text=True) and 'An error occurred' not in response.get_data(as_text=True)
    _assert_logged(caplog, 'offer_page 7')


def test_e3_cyprus_unexpected_errors_are_generic_but_integration_errors_keep_their_message(app, monkeypatch, caplog):
    from InvestmentWebsite.blueprints.cyprus import cyprus as module
    monkeypatch.setattr(module, 'fetch_projects', _boom)
    monkeypatch.setattr(module, 'fetch_project_details', _boom)
    client = app.test_client()
    for url in ('/api/cyprus_projects', '/api/cyprus_project_details?url=https://example.test/p'):
        response = client.get(url)
        assert response.status_code == 502 and SECRET not in response.get_data(as_text=True)
    _assert_logged(caplog, 'cyprus.projects')
    monkeypatch.setattr(module, 'fetch_projects', lambda *a, **k: (_ for _ in ()).throw(module.CyprusConstructionsError('Źródło danych niedostępne.')))
    deliberate = client.get('/api/cyprus_projects')
    assert deliberate.status_code == 500 and deliberate.get_json()['error'] == 'Źródło danych niedostępne.'


# ------------------------------------------------------------------------------------------------ CRM
def test_e4_agent_admin_errors_are_generic_and_deliberate_ones_are_kept(app, crm_env, crm_login, monkeypatch, caplog):
    from InvestmentManager.integrator.input_consistency import ConsistencyError
    from InvestmentManager.routes import agents as module
    master = crm_login(app, CRM_MASTER)
    monkeypatch.setattr(module, 'write_inputs', _boom)
    for call in (lambda: master.delete(f'/crm/delete_agent/{CRM_ANN}'),
                 lambda: master.post(f'/crm/update_agent/{CRM_ANN}', data={'imie': 'A', 'nazwisko': 'B'}),
                 lambda: master.post('/crm/add_agent', data={'imie': 'Nowy', 'nazwisko': 'Agent'})):
        response = call()
        body = response.get_json()
        assert response.status_code == 500 and SECRET not in response.get_data(as_text=True)
        assert body['status'] == 'error' and body['message'] == 'Wystąpił błąd serwera.' and body['request_id']
    _assert_logged(caplog, 'agents.')
    monkeypatch.setattr(module, 'write_inputs', lambda **kw: (_ for _ in ()).throw(ConsistencyError('Dane eksportu są zajęte. Ponów operację.')))
    deliberate = master.delete(f'/crm/delete_agent/{CRM_ANN}')
    assert deliberate.status_code == 500 and deliberate.get_json()['message'] == 'Dane eksportu są zajęte. Ponów operację.'
    assert master.post(f'/crm/change_password/{CRM_ANN}', data={}).get_json() == {'status': 'error', 'message': 'Brak hasła.'}         # validation unchanged


def test_e4_change_password_unexpected_error_is_generic(app, crm_env, crm_login, monkeypatch):
    from InvestmentManager.routes import agents as module
    master = crm_login(app, CRM_MASTER)
    monkeypatch.setattr(module, 'generate_password_hash', _boom)
    response = master.post(f'/crm/change_password/{CRM_ANN}', data={'new_password': 'x' * 12})
    assert response.status_code == 500 and SECRET not in response.get_data(as_text=True) and response.get_json()['request_id']


def test_e5_leady_inbox_errors_are_generic_but_validation_errors_are_kept(app, crm_env, crm_login, monkeypatch, caplog):
    from InvestmentManager.routes import leady_logs as module

    @contextlib.contextmanager
    def fake_connection():
        class Conn:
            def commit(self):
                pass
        yield Conn()

    monkeypatch.setattr(module, 'open_leady_connection', fake_connection)
    master = crm_login(app, CRM_MASTER)
    monkeypatch.setattr(module, 'convert_inbox_to_crm_lead', _boom)
    monkeypatch.setattr(module, 'update_inbox_status', _boom)
    for response in (master.post('/crm/leady/inbox/5/convert', json={}), master.patch('/crm/leady/inbox/5', json={'inbox_status': 'x'})):
        _assert_clean(response, status=500)
    _assert_logged(caplog, 'leady.')
    monkeypatch.setattr(module, 'convert_inbox_to_crm_lead', lambda *a, **k: (_ for _ in ()).throw(ValueError('Lead już istnieje.')))
    monkeypatch.setattr(module, 'update_inbox_status', lambda *a, **k: (_ for _ in ()).throw(ValueError('Nieprawidłowy status.')))
    assert master.post('/crm/leady/inbox/5/convert', json={}).get_json() == {'error': 'Lead już istnieje.'}
    assert master.patch('/crm/leady/inbox/5', json={'inbox_status': 'x'}).get_json() == {'error': 'Nieprawidłowy status.'}


def test_e6_calendar_errors_are_generic(app, crm_env, crm_login, monkeypatch, caplog):
    from InvestmentManager.routes import agent_panel_scheduler as module
    ann = crm_login(app, CRM_ANN)
    created = ann.post('/crm/agent_panel/add_event', json={'title': 't', 'start': '2030-01-01'}).get_json()['event']
    monkeypatch.setattr(module, 'backup_schedule', _boom)
    responses = [ann.post('/crm/agent_panel/add_event', json={'title': 'x', 'start': '2030-01-01'}),
                 ann.post('/crm/agent_panel/update_event', json={'id': created['id'], 'title': 'y'}),
                 ann.post('/crm/agent_panel/delete_event', json={'id': created['id']})]
    for response in responses:
        _assert_clean(response, status=500)
    assert [r.get_json()['error'] for r in responses] == ['Błąd zapisu.', 'Błąd edycji.', 'Błąd usuwania.']
    _assert_logged(caplog, 'agent_panel.')


def test_e7_foreign_offer_sync_errors_are_generic_but_domain_errors_are_kept(app, crm_env, crm_login, monkeypatch, caplog):
    from InvestmentManager.routes import foreign_offers as module
    monkeypatch.setattr(module, 'initialize_foreign_offers_db', lambda: None)
    master = crm_login(app, CRM_MASTER)
    monkeypatch.setattr(module, 'run_foreign_source_sync', _boom)
    response = master.post('/crm/foreign-offers/sync/avarten')
    assert response.status_code == 500 and SECRET not in response.get_data(as_text=True)
    assert response.get_json()['ok'] is False and response.get_json()['error'] == 'Synchronizacja nie powiodła się.' and response.get_json()['request_id']
    _assert_logged(caplog, 'foreign_offers.sync')
    monkeypatch.setattr(module, 'run_foreign_source_sync', lambda source: (_ for _ in ()).throw(module.ForeignSyncFailed('Źródło odrzuciło logowanie.')))
    deliberate = master.post('/crm/foreign-offers/sync/avarten')
    assert deliberate.status_code == 502 and deliberate.get_json() == {'ok': False, 'error': 'Źródło odrzuciło logowanie.'}


def test_e7_refresh_all_reports_generic_errors_per_offer(app, crm_env, crm_login, monkeypatch, caplog):
    from InvestmentManager.routes import foreign_offers as module

    rows = [{'id': 1, 'source_url': 'https://example.test/1'}, {'id': 2, 'source_url': ''}]
    monkeypatch.setattr(module, 'initialize_foreign_offers_db', lambda: None)
    monkeypatch.setattr(module, 'list_active_tripinvest_refresh_rows', lambda: rows)       # S4.7/P1: the row source moved into foreign_offers_store
    monkeypatch.setattr(module, 'upsert_foreign_offer_from_tripinvest', _boom)
    body = crm_login(app, CRM_MASTER).post('/crm/foreign-offers/refresh-all').get_json()
    assert SECRET not in str(body)
    assert body['ok'] is False and body['error_count'] == 2
    assert body['errors'][0]['error'] == 'Nie udało się odświeżyć oferty.' and body['errors'][0]['request_id']
    assert body['errors'][1] == {'id': 2, 'error': 'Brak source_url.'}                  # deliberate message kept
    _assert_logged(caplog, 'foreign_offers.refresh_all')
