"""S4.7 / package 1: characterization of the CRM reads of `platform_logs` (leady_logs routes and leady_pipeline inbox sync).

Passing on the OLD code; must pass unchanged after the two SELECTs move to `modules.core.platform_log_queries`.
Own throw-away database (`storage_paths.platform_logs_db_path` is pointed to tmp for the test).
"""
import json
import sqlite3

import pytest

from InvestmentManager import leady_pipeline as pipeline
from modules.core import storage_paths

SCHEMA = """CREATE TABLE platform_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TEXT NOT NULL, log_type TEXT NOT NULL,
            path TEXT, status TEXT, payload TEXT NOT NULL)"""


@pytest.fixture()
def db(tmp_path, monkeypatch):
    path = tmp_path / 'platform_logs.db'
    monkeypatch.setattr(storage_paths, 'platform_logs_db_path', lambda: path)
    monkeypatch.setattr(storage_paths, 'platform_logs_dir', lambda: tmp_path)
    return path


def seed(db, rows):
    conn = sqlite3.connect(db)
    conn.execute(SCHEMA)
    conn.executemany('INSERT INTO platform_logs (created_at, log_type, path, status, payload) VALUES (?,?,?,?,?)', rows)
    conn.commit()
    conn.close()


def lead(platform, phone, **extra):
    return json.dumps({'platform': platform, 'phone': phone, 'event': 'lead_sent', 'offer_url': 'https://example.invalid/o', **extra})


ROWS = [
    ('2030-01-01T10:00:00', 'leads', '/api/lead', 'sent', lead('otodom', '600')),                                   # id 1
    ('2030-01-02T10:00:00', 'phone_views', '/api/phone', None, json.dumps({'platform': 'otodom', 'event': 'phone_view', 'status': 'ok'})),  # 2 status from payload
    ('2030-01-03T10:00:00', 'errors', None, '', json.dumps({'platform': 'domiporta', 'event': 'boom'})),            # 3 NULL path, empty status
    ('2030-01-04T10:00:00', 'leads', '/api/lead', 'sent', '{broken json'),                                          # 4 invalid payload
    ('2030-01-05T10:00:00', 'leads', '/api/lead', 'sent', ''),                                                      # 5 empty payload
    ('2030-01-06T10:00:00', 'general', '/x', 'x', json.dumps({'platform': 'gruntguru'})),                           # 6
]


@pytest.fixture()
def master(client):
    with client.session_transaction() as sess:
        sess['user_id'] = 1
        sess['access_level'] = 'master'
    return client


def items(response):
    return response.get_json()['items']


# ----------------------------------------------------------------------------------------------------------- the panel route
def test_without_a_database_file_stats_are_empty_and_the_list_route_raises_in_the_inbox_sync(master, db):
    stats = master.get('/crm/leady/platform_logs/stats').get_json()
    assert stats['totals'] == {'logs': 0, 'leads_sent': 0, 'phone_views': 0, 'error_events': 0, 'conversion_percent': 0.0}
    assert not db.exists()                                                          # the read does not create the file
    # the list route reads [] first, but then opens the leady connection (creates the file) and the sync needs the table
    with pytest.raises(sqlite3.OperationalError, match='no such table: platform_logs'):
        master.get('/crm/leady/platform_logs')


def test_the_list_is_newest_id_first_with_the_exact_item_shape(master, db):
    seed(db, ROWS)
    body = master.get('/crm/leady/platform_logs').get_json()
    assert [i['id'] for i in body['items']] == [6, 5, 4, 3, 2, 1] and body['meta']['total'] == 6
    first = body['items'][5]                                                    # id 1: a lead, synced into the inbox by the route
    assert set(first) == {'id', 'created_at', 'log_type', 'platform', 'event', 'status', 'offer_url', 'platform_page_url', 'email', 'phone',
                          'phone_message', 'ip', 'path', 'payload', 'inbox_id', 'inbox_status', 'assigned_agent_id', 'crm_lead_id',
                          'inbox_notes', 'crm_lead_name', 'crm_lead_priority'}
    assert (first['platform'], first['phone'], first['event'], first['status'], first['path']) == ('otodom', '600', 'lead_sent', 'sent', '/api/lead')
    assert first['inbox_id'] is not None and first['inbox_status'] == 'new'


def test_nulls_empty_values_and_broken_payloads_are_normalised(master, db):
    seed(db, ROWS)
    by_id = {i['id']: i for i in items(master.get('/crm/leady/platform_logs'))}
    assert by_id[2]['status'] == 'ok' and by_id[2]['inbox_id'] is None and by_id[2]['inbox_status'] == ''     # status from the payload; no inbox for non-leads
    assert by_id[3]['path'] == '' and by_id[3]['status'] == ''
    assert by_id[4]['payload'] == {} and by_id[4]['platform'] == '' and by_id[4]['inbox_id'] is not None      # invalid JSON -> {}, lead still synced
    assert by_id[5]['payload'] == {} and by_id[5]['log_type'] == 'leads'                                        # empty payload -> {}


def test_filters_and_paging(master, db):
    seed(db, ROWS)
    ids = lambda query: [i['id'] for i in items(master.get('/crm/leady/platform_logs' + query))]
    assert ids('?platform=otodom') == [2, 1] and ids('?log_scope=leads') == [5, 4, 1] and ids('?log_scope=non_leads') == [6, 3, 2]
    assert ids('?log_type=errors') == [3] and ids('?event=boom') == [3] and ids('?status=ok') == [2]
    assert ids('?query=gruntguru') == [6] and ids('?query=otodom') == [2, 1]
    assert ids('?date_from=2030-01-04') == [6, 5, 4] and ids('?date_to=2030-01-03') == [3, 2, 1]
    assert ids('?per_page=2') == [6, 5] and ids('?per_page=2&page=2') == [4, 3] and ids('?per_page=0&page=0') == [6]
    assert master.get('/crm/leady/platform_logs?per_page=2').get_json()['meta'] == {'page': 1, 'per_page': 2, 'total': 6, 'total_pages': 3}


def test_the_stats_route_aggregates_the_same_rows(master, db):
    seed(db, ROWS)
    body = master.get('/crm/leady/platform_logs/stats').get_json()
    assert body['totals'] == {'logs': 6, 'leads_sent': 3, 'phone_views': 1, 'error_events': 1, 'conversion_percent': 300.0}
    assert body['by_type'] == {'general': 1, 'leads': 3, 'errors': 1, 'phone_views': 1}
    assert body['by_platform'] == {'gruntguru': 1, '-': 2, 'domiporta': 1, 'otodom': 2} and body['by_status'] == {'x': 1, 'sent': 3, '-': 1, 'ok': 1}
    assert master.get('/crm/leady/platform_logs/stats?platform=otodom').get_json()['totals']['logs'] == 2


def test_permissions_are_unchanged(client, db):
    seed(db, ROWS)
    assert client.get('/crm/leady/platform_logs').status_code in (302, 401, 403)
    with client.session_transaction() as sess:
        sess['user_id'] = 2
        sess['access_level'] = 'agent'
    assert client.get('/crm/leady/platform_logs').status_code == 403
    assert client.get('/crm/leady/platform_logs/stats').status_code == 403


def test_a_database_without_the_table_raises_the_sqlite_error(master, db):
    sqlite3.connect(db).close()                                                  # exists, empty
    with pytest.raises(sqlite3.OperationalError, match='no such table: platform_logs'):
        master.get('/crm/leady/platform_logs')


# ----------------------------------------------------------------------------------------------------------- inbox sync (leady_pipeline)
def inbox(conn):
    return [tuple(r) for r in conn.execute('SELECT platform_log_id, platform, phone, email, offer_url, inbox_status FROM lead_inbox ORDER BY platform_log_id')]


def test_sync_copies_only_new_lead_logs_in_id_order_and_is_idempotent(db):
    seed(db, ROWS)
    with pipeline.open_leady_connection() as conn:
        assert pipeline.sync_inbox_from_platform_logs(conn) == 3
        assert inbox(conn) == [(1, 'otodom', '600', None, 'https://example.invalid/o', 'new'), (4, None, None, None, None, 'new'),
                               (5, None, None, None, None, 'new')]                       # broken / empty payload -> NULL fields, row kept
        assert pipeline.sync_inbox_from_platform_logs(conn) == 0
        conn.execute("INSERT INTO platform_logs (created_at, log_type, path, status, payload) VALUES ('2030-02-01T00:00:00','leads','/l','sent',?)",
                     (lead('domiporta', '700', email='a@example.invalid'),))
        conn.execute("INSERT INTO platform_logs (created_at, log_type, path, status, payload) VALUES ('2030-02-02T00:00:00','errors','/e','e','{}')")
        assert pipeline.sync_inbox_from_platform_logs(conn) == 1
        assert inbox(conn)[-1] == (7, 'domiporta', '700', 'a@example.invalid', 'https://example.invalid/o', 'new')


def test_sync_only_looks_at_ids_after_the_newest_inbox_row(db):
    seed(db, ROWS)
    with pipeline.open_leady_connection() as conn:
        conn.execute("INSERT INTO lead_inbox (platform_log_id, created_at, inbox_status) VALUES (4, '2030-01-04T00:00:00', 'ignored')")
        assert pipeline.sync_inbox_from_platform_logs(conn) == 1                       # only id 5 is newer than 4; ids 1 stays unsynced
        assert [row[0] for row in inbox(conn)] == [4, 5]


def test_sync_with_a_missing_platform_logs_table_raises(db):
    with pipeline.open_leady_connection() as conn:
        with pytest.raises(sqlite3.OperationalError, match='no such table: platform_logs'):
            pipeline.sync_inbox_from_platform_logs(conn)


def test_the_connection_helpers_still_resolve_the_shared_file(db):
    assert not hasattr(pipeline, 'DB_PATH')
    with pipeline.open_leady_connection() as conn:
        conn.execute('SELECT 1')
    assert db.exists()
