"""S4.1 characterization: the three read queries that used to run SQL inside CRM routes.

Pins the observable behaviour (result structure, order, filters, NULL handling, failure handling) so that moving the SQL out of the
HTTP layer cannot change it. These tests were written and passed BEFORE the migration and must pass unchanged AFTER it.

Synthetic data only (tmp DATA_DIR from the `crm_env` fixture).
"""
import sqlite3

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 _idb():
    return sqlite3.connect(storage_paths.idb_db_path())


def _agents():
    return sqlite3.connect(storage_paths.agents_db_path())


# ---------------------------------------------------------------------------------------------------------------------
# lead_hunter_seekers.get_estates_for_leads  (SELECT * FROM EstateData WHERE Status_oferty = "aktywna" ORDER BY ID DESC LIMIT ?)
# ---------------------------------------------------------------------------------------------------------------------

@pytest.fixture()
def estates(crm_env):
    conn = _idb()
    conn.executescript("DROP TABLE estatedata; CREATE TABLE EstateData (ID INTEGER PRIMARY KEY, ID_agenta INTEGER, Status_oferty TEXT, Tytul TEXT, Cena TEXT);")
    conn.executemany("INSERT INTO EstateData VALUES (?,?,?,?,?)", [
        (1, 102, 'aktywna', 'one', '100'),
        (2, 102, 'Aktywna', 'wrong case', '1'),       # case-sensitive comparison: excluded
        (3, 103, 'aktywna ', 'trailing space', '2'),  # exact comparison: excluded
        (4, 103, 'nieaktywna', 'inactive', '3'),
        (5, None, 'aktywna', 'no owner', None),       # NULL columns are returned as None, the row is kept
        (6, 103, None, 'null status', '4'),           # NULL status: excluded
        (7, 102, 'aktywna', 'seven', '700'),
        (9, 103, 'aktywna', 'nine', '900'),
    ])
    conn.commit()
    conn.close()
    return crm_env


def _estates(limit=None):
    from InvestmentManager.routes import lead_hunter_seekers
    return lead_hunter_seekers.get_estates_for_leads() if limit is None else lead_hunter_seekers.get_estates_for_leads(limit=limit)


def test_estates_are_active_only_newest_id_first_as_plain_dicts_with_every_column(estates):
    rows = _estates()
    assert [r['ID'] for r in rows] == [9, 7, 5, 1]
    assert all(type(r) is dict for r in rows)
    assert list(rows[0]) == ['ID', 'ID_agenta', 'Status_oferty', 'Tytul', 'Cena']          # table column order, SELECT *
    assert rows[0] == {'ID': 9, 'ID_agenta': 103, 'Status_oferty': 'aktywna', 'Tytul': 'nine', 'Cena': '900'}


def test_estates_keep_null_columns_as_none_and_filter_is_exact(estates):
    by_id = {r['ID']: r for r in _estates()}
    assert by_id[5] == {'ID': 5, 'ID_agenta': None, 'Status_oferty': 'aktywna', 'Tytul': 'no owner', 'Cena': None}
    assert not {2, 3, 4, 6} & set(by_id)                  # wrong case, trailing space, inactive, NULL status


@pytest.mark.parametrize('limit, expected', [(1, [9]), (2, [9, 7]), (3, [9, 7, 5]), (4, [9, 7, 5, 1]), (100, [9, 7, 5, 1]),
                                             (0, []), (-1, [9, 7, 5, 1])])
def test_estates_limit_is_applied_after_ordering(estates, limit, expected):
    assert [r['ID'] for r in _estates(limit)] == expected     # LIMIT 0 -> nothing; a negative LIMIT is "no limit" in SQLite


def test_estates_default_limit_is_100(crm_env):
    conn = _idb()
    conn.executescript("DROP TABLE estatedata; CREATE TABLE EstateData (ID INTEGER PRIMARY KEY, Status_oferty TEXT);")
    conn.executemany("INSERT INTO EstateData VALUES (?, 'aktywna')", [(i,) for i in range(1, 131)])
    conn.commit()
    conn.close()
    rows = _estates()
    assert len(rows) == 100 and rows[0]['ID'] == 130 and rows[-1]['ID'] == 31


def test_estates_empty_table_gives_an_empty_list(crm_env):
    conn = _idb()
    conn.executescript("DROP TABLE estatedata; CREATE TABLE EstateData (ID INTEGER PRIMARY KEY, Status_oferty TEXT);")
    conn.commit()
    conn.close()
    assert _estates() == []


def test_estates_missing_table_raises_the_sqlite_error_unchanged(crm_env):
    conn = _idb()
    conn.execute("DROP TABLE estatedata")
    conn.commit()
    conn.close()
    with pytest.raises(sqlite3.OperationalError, match='no such table'):
        _estates()


def test_estates_connection_failure_propagates_unchanged(crm_env, monkeypatch):
    from modules import classes
    monkeypatch.setattr(classes, 'connection', lambda db_target=None: (_ for _ in ()).throw(sqlite3.OperationalError('fail')))
    with pytest.raises(sqlite3.OperationalError, match='fail'):
        _estates()


# ---------------------------------------------------------------------------------------------------------------------
# knowledge_center.get_all_agent_ids  (SELECT id FROM agents_v2 WHERE is_active = 1)
# ---------------------------------------------------------------------------------------------------------------------

@pytest.fixture()
def agents(crm_env):
    conn = _agents()
    conn.executemany("INSERT INTO agents_v2 (id, login, is_active) VALUES (?,?,?)",
                     [(110, 'inactive', 0), (111, 'null_flag', None), (112, 'active2', 1), (113, 'flag2', 2)])
    conn.commit()
    conn.close()
    return crm_env


def _ids(app, **kwargs):
    from InvestmentManager.routes import knowledge_center
    with app.app_context():
        return knowledge_center.get_all_agent_ids(**kwargs)


def test_agent_ids_are_the_active_agents_only(app, agents):
    assert _ids(app) == [CRM_MASTER, CRM_ANN, CRM_BOB, 112]                # id order of the table; 0 / NULL / 2 are not active


def test_agent_ids_can_exclude_one_user_and_exclusion_of_an_unknown_id_changes_nothing(app, agents):
    assert _ids(app, exclude_user_id=CRM_ANN) == [CRM_MASTER, CRM_BOB, 112]
    assert _ids(app, exclude_user_id=99999) == [CRM_MASTER, CRM_ANN, CRM_BOB, 112]
    assert _ids(app, exclude_user_id=0) == [CRM_MASTER, CRM_ANN, CRM_BOB, 112]   # `is not None`: 0 is a real exclusion value


def test_agent_ids_without_agents_table_degrade_to_an_empty_list_and_log(app, crm_env, caplog):
    conn = _agents()
    conn.execute("DROP TABLE agents_v2")
    conn.commit()
    conn.close()
    with caplog.at_level('ERROR'):
        assert _ids(app) == []
    assert any('get_all_agent_ids' in r.getMessage() for r in caplog.records)


# ---------------------------------------------------------------------------------------------------------------------
# agent_panel.get_offer_summary  (GET /crm/offers/summary -> SELECT Status_oferty FROM estatedata WHERE ID_agenta = ?)
# ---------------------------------------------------------------------------------------------------------------------

def _set_offers(rows):
    conn = _idb()
    conn.execute("DELETE FROM estatedata")
    conn.executemany("INSERT INTO estatedata (ID, ID_agenta, Status_oferty) VALUES (?,?,?)", rows)
    conn.commit()
    conn.close()


def test_offer_summary_counts_statuses_of_the_caller_only(app, crm_env, crm_login):
    _set_offers([(1, CRM_ANN, 'aktywna'), (2, CRM_ANN, 'aktywna'), (3, CRM_ANN, 'nieaktywna'), (4, CRM_ANN, 'Aktywna'),
                 (5, CRM_BOB, 'aktywna'), (6, CRM_MASTER, 'sprzedana')])
    ann = crm_login(app, CRM_ANN).get('/crm/offers/summary')
    assert ann.status_code == 200 and ann.get_json() == {'Aktywna': 1, 'aktywna': 2, 'nieaktywna': 1}     # case-sensitive keys
    assert crm_login(app, CRM_BOB).get('/crm/offers/summary').get_json() == {'aktywna': 1}
    assert crm_login(app, CRM_MASTER).get('/crm/offers/summary').get_json() == {'sprzedana': 1}


def test_offer_summary_of_an_agent_without_offers_is_an_empty_object(app, crm_env, crm_login):
    _set_offers([(5, CRM_BOB, 'aktywna')])
    response = crm_login(app, CRM_ANN).get('/crm/offers/summary')
    assert response.status_code == 200 and response.get_json() == {}


def test_offer_summary_with_a_null_status_is_a_server_error_today(app, crm_env, crm_login):
    """Current behaviour (kept, not endorsed): a NULL status becomes a None key; mixing it with text keys cannot be sorted by
    jsonify, the route's broad except turns it into the generic 500."""
    _set_offers([(1, CRM_ANN, 'aktywna'), (2, CRM_ANN, None)])
    response = crm_login(app, CRM_ANN).get('/crm/offers/summary')
    assert response.status_code == 500 and response.get_json() == {'error': 'Błąd serwera'}


def test_offer_summary_database_failure_is_the_generic_500(app, crm_env, crm_login):
    client = crm_login(app, CRM_ANN)
    conn = _idb()
    conn.execute("DROP TABLE estatedata")
    conn.commit()
    conn.close()
    response = client.get('/crm/offers/summary')
    assert response.status_code == 500 and response.get_json() == {'error': 'Błąd serwera'}
