"""S4.7 / package 1: the moved reads (platform_logs for the CRM, two foreign_offers lookups) and the shape of the code that uses them."""
import ast
import sqlite3
from pathlib import Path

import pytest

from InvestmentManager import foreign_offers_store as store
from modules.core import platform_log_queries as queries
from tests.investmentmanager.test_s47p1_foreign_refresh_characterization import add  # noqa: F401
from tests.investmentmanager.test_s47p1_platform_logs_characterization import ROWS, db, seed  # noqa: F401
from tests.investmentmanager.test_foreign_offer_refresh_guard import refresh_db  # noqa: F401
from tests.investmentmanager.test_foreign_developments_routes import foreign_db  # noqa: F401

ROOT = Path(__file__).resolve().parents[2]


def test_platform_log_rows_are_newest_first_sqlite_rows_and_empty_without_a_file(db):
    assert queries.list_platform_log_rows() == [] and not db.exists()
    seed(db, ROWS)
    rows = queries.list_platform_log_rows()
    assert [r['id'] for r in rows] == [6, 5, 4, 3, 2, 1] and isinstance(rows[0], sqlite3.Row)
    assert rows[0].keys() == ['id', 'created_at', 'log_type', 'path', 'status', 'payload']


def test_a_database_without_the_table_raises(db):
    sqlite3.connect(db).close()
    with pytest.raises(sqlite3.OperationalError, match='no such table: platform_logs'):
        queries.list_platform_log_rows()


def test_lead_rows_after_an_id_are_read_on_the_callers_connection_oldest_first(db):
    seed(db, ROWS)
    conn = sqlite3.connect(db)
    conn.row_factory = sqlite3.Row
    rows = queries.list_lead_log_rows_after(conn, 1)
    assert [r['id'] for r in rows] == [4, 5] and rows[0].keys() == ['id', 'created_at', 'payload']
    assert queries.list_lead_log_rows_after(conn, 5) == []
    conn.close()


def test_the_leads_routes_and_the_pipeline_no_longer_run_sql_on_platform_logs():
    for path in ('InvestmentManager/routes/leady_logs.py', 'InvestmentManager/leady_pipeline.py'):
        tree = ast.parse((ROOT / path).read_text(encoding='utf-8-sig'))
        for node in ast.walk(tree):
            if isinstance(node, ast.Constant) and isinstance(node.value, str):
                assert 'FROM platform_logs' not in node.value, path
    assert 'sqlite3' not in (ROOT / 'InvestmentManager/routes/leady_logs.py').read_text(encoding='utf-8-sig')


def test_the_foreign_lookups_return_rows_in_the_documented_shape(refresh_db):
    store.initialize_foreign_offers_db()
    row = store.get_foreign_offer_refresh_row(1)
    assert row.keys() == ['id', 'source_platform', 'source_url'] and row['source_platform'] == 'tripinvest'
    assert store.get_foreign_offer_refresh_row(999) is None and store.get_foreign_offer_refresh_row('1')['id'] == 1
    add(refresh_db, (9, 'tripinvest', 'https://tripinvest.pl/oferta/nine', True), (3, 'tripinvest', 'https://tripinvest.pl/oferta/three', True),
        (4, 'tripinvest', 'https://tripinvest.pl/oferta/off', False))
    rows = store.list_active_tripinvest_refresh_rows()
    assert [r['id'] for r in rows] == [1, 3, 9] and rows[0].keys() == ['id', 'source_url']


def test_the_foreign_routes_no_longer_run_sql():
    tree = ast.parse((ROOT / 'InvestmentManager/routes/foreign_offers.py').read_text(encoding='utf-8-sig'))
    assert not [n for n in ast.walk(tree) if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and n.func.attr in ('execute', 'executemany')]
