"""S3 / H1-H3: a failure is never presented as a valid empty result; notification failures are logged and do not change the
result reported for the note / comment that was saved."""
import json
import logging
import sqlite3

import pytest

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

pytestmark = pytest.mark.crm_session_guard


# ------------------------------------------------------------------------------------------------ H1 districts
def test_h1_districts_failure_is_a_503_not_an_empty_list(app, crm_env, crm_login, monkeypatch, caplog):
    from InvestmentManager.routes import offer_catalog
    ann = crm_login(app, CRM_ANN)
    with monkeypatch.context() as patch:
        patch.setattr(offer_catalog, '_get_location_values', lambda *a, **k: (_ for _ in ()).throw(sqlite3.OperationalError('database is locked')))
        with caplog.at_level(logging.ERROR):
            response = ann.get('/crm/offers/districts/mazowieckie')
    body = response.get_json()
    assert response.status_code == 503 and body['code'] == 'location_lookup_failed' and body['request_id'] and 'locked' not in json.dumps(body)
    assert any('database is locked' in r.getMessage() and 'request_id=' in r.getMessage() for r in caplog.records)


def test_h1_districts_normal_and_empty_region_answers_are_unchanged(app, crm_env, crm_login, monkeypatch):
    from InvestmentManager.routes import offer_catalog
    ann = crm_login(app, CRM_ANN)
    monkeypatch.setattr(offer_catalog, '_get_location_values', lambda column, **k: ['powiat A', 'powiat B'])
    assert ann.get('/crm/offers/districts/mazowieckie').get_json() == ['powiat A', 'powiat B']
    assert ann.get('/crm/offers/districts').get_json() == []                    # no region selected: genuinely nothing to list


# ------------------------------------------------------------------------------------------------ H2 notification recipients
def test_h2_get_all_agent_ids_failure_is_logged_with_request_id_and_keeps_the_empty_contract(app, crm_env, caplog):
    from flask import g
    from InvestmentManager.routes import knowledge_center
    conn = sqlite3.connect(storage_paths.agents_db_path())
    conn.execute('DROP TABLE agents_v2')
    conn.commit()
    conn.close()
    with app.test_request_context('/crm/knowledge/add_note', method='POST'):
        g.request_id = 'rid123'
        with caplog.at_level(logging.ERROR):
            assert knowledge_center.get_all_agent_ids(exclude_user_id=CRM_ANN) == []
    messages = [r.getMessage() for r in caplog.records if r.levelno >= logging.ERROR]
    assert any('get_all_agent_ids' in m and 'request_id=rid123' in m and 'agents_v2' in m for m in messages), messages


def test_h2_note_and_comment_are_reported_as_saved_when_recipients_cannot_be_read(app, crm_env, crm_login, monkeypatch):
    from InvestmentManager.routes import knowledge_center
    ann = crm_login(app, CRM_ANN)
    monkeypatch.setattr(knowledge_center, 'get_all_agent_ids', lambda exclude_user_id=None: [])        # what the helper returns on failure
    response = ann.post('/crm/knowledge/add_note', json={'title': 'public', 'content': 'c', 'is_private': False})
    assert response.status_code == 200 and response.get_json() == {'message': 'Notatka zapisana'}
    notes = json.loads(storage_paths.knowledge_center_notes_path().read_text(encoding='utf-8'))
    assert [n['title'] for n in notes] == ['public']
    ts = notes[0]['timestamp']
    assert ann.post('/crm/knowledge/add_comment', json={'note_timestamp': ts, 'comment': 'x'}).get_json() == {'message': 'Komentarz zapisany'}
