"""S4.7 / package 2: `InvestmentManager/agents_store.py` owns the agents-directory SQL; the routes, the own-profile update and the login lookup
no longer contain any, and the DB Shell lives in `routes/dbshell.py`. Shape of the code plus direct tests of the store on a throw-away database."""
import ast
import sqlite3
from pathlib import Path

import pytest

from InvestmentManager import agents_store as store

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


def parse(path):
    return ast.parse((ROOT / path).read_text(encoding='utf-8-sig'))


def sql_calls(tree):
    return [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', 'executescript')]


@pytest.mark.parametrize('path', ['InvestmentManager/routes/agents.py', 'InvestmentManager/middleware/auth.py', 'InvestmentManager/routes/dashboard.py'])
def test_the_http_layer_of_the_agents_domain_runs_no_sql(path):
    assert sql_calls(parse(path)) == []


def test_the_store_has_no_http_session_or_password_dependencies():
    imported = set()
    for node in ast.walk(parse('InvestmentManager/agents_store.py')):
        if isinstance(node, ast.Import):
            imported.update(alias.name.split('.')[0] for alias in node.names)
        elif isinstance(node, ast.ImportFrom):
            imported.add((node.module or '').split('.')[0])
    assert imported == set()                                                    # nothing: no flask, no werkzeug, no sibling module


def test_the_db_shell_moved_out_of_the_dashboard_with_the_same_routes():
    dashboard = (ROOT / 'InvestmentManager/routes/dashboard.py').read_text(encoding='utf-8-sig')
    dbshell = (ROOT / 'InvestmentManager/routes/dbshell.py').read_text(encoding='utf-8-sig')
    assert "'/dbshell/" not in dashboard and 'DB_SHELL' not in dashboard and 'hmac' not in dashboard
    routes = [n for n in ast.walk(ast.parse(dbshell)) if isinstance(n, ast.FunctionDef) and any('route' in ast.unparse(d) for d in n.decorator_list)]
    assert sorted(f.name for f in routes) == sorted([
        'dbshell_status', 'dbshell_unlock', 'dbshell_lock', 'dbshell_tables', 'dbshell_table_data', 'dbshell_update_cell',
        'dbshell_orphan_offer_folders', 'dbshell_delete_orphan_offer_folder', 'dbshell_find_duplicates', 'dbshell_replace_text'])
    assert 'def dbshell_ui' in dashboard                                         # the page itself still renders the dashboard context


@pytest.fixture()
def cursor():
    conn = sqlite3.connect(':memory:')
    conn.executescript(
        "CREATE TABLE agents_v2 (id INTEGER PRIMARY KEY, login TEXT, password_hash TEXT, first_name TEXT, last_name TEXT, email TEXT, phone TEXT,"
        " license TEXT, access_level TEXT, is_active INTEGER, created_at TEXT, updated_at TEXT);"
        "CREATE TABLE branches_v2 (id INTEGER PRIMARY KEY, code TEXT, name TEXT, title TEXT, image_url TEXT, info1 TEXT, info2 TEXT, is_active INTEGER,"
        " created_at TEXT, updated_at TEXT);"
        "CREATE TABLE roles_v2 (id INTEGER PRIMARY KEY, code TEXT, name TEXT, description TEXT, is_active INTEGER);"
        "CREATE TABLE agent_branches_v2 (agent_id INTEGER, branch_id INTEGER, is_primary INTEGER, created_at TEXT);"
        "CREATE TABLE agent_roles_v2 (agent_id INTEGER, role_id INTEGER, created_at TEXT);")
    yield conn.cursor()
    conn.close()


def test_slug_and_int_list_helpers():
    assert store.to_int_list(['1', ' 2 ', 'x', None, 3, '4.5']) == [1, 2, 3]
    assert store._normalize_branch_code('Łódź  Śródmieście / Północ') == 'lodz-srodmiescie-polnoc'
    assert store._normalize_role_code('???') == 'rola' and store._normalize_branch_code('') == 'oddzial' and store._normalize_branch_code(None) == 'oddzial'


def test_ensure_role_reuses_by_name_and_numbers_colliding_codes(cursor):
    first = store.ensure_role(cursor, ' Doradca ')
    assert store.ensure_role(cursor, 'doradca') == first and store.ensure_role(cursor, '') is None and store.ensure_role(cursor, None) is None
    second = store.ensure_role(cursor, 'Doradca!')
    assert second != first
    assert [r[0] for r in cursor.execute('SELECT code FROM roles_v2 ORDER BY id')] == ['doradca', 'doradca-2']
    assert cursor.execute('SELECT description, is_active FROM roles_v2 WHERE id=?', (first,)).fetchone() == ('', 1)


def test_next_agent_id_sync_and_delete(cursor):
    assert store.next_agent_id(cursor) == 1
    store.insert_agent(cursor, 7, 'a.b', 'h', 'A', 'B', None, None, None, 'agent', 't')
    assert store.next_agent_id(cursor) == 8 and store.get_agent_editable_row(cursor, 7) == ('A', 'B', None, None, None, 'agent')
    assert store.get_agent_editable_row(cursor, 99) is None and store.get_agent_contact_row(cursor, 7) == (None, None, None)
    store.sync_agent_branches(cursor, 7, [5, 3], 't')
    store.sync_agent_roles(cursor, 7, [2], 't')
    assert cursor.execute('SELECT branch_id, is_primary FROM agent_branches_v2 ORDER BY rowid').fetchall() == [(5, 1), (3, 0)]
    store.sync_agent_branches(cursor, 7, [], 't')
    assert cursor.execute('SELECT COUNT(*) FROM agent_branches_v2').fetchone() == (0,)
    store.delete_agent_rows(cursor, 7)
    assert [cursor.execute(f'SELECT COUNT(*) FROM {t}').fetchone()[0] for t in ('agents_v2', 'agent_roles_v2', 'agent_branches_v2')] == [0, 0, 0]


def test_login_lookup_and_password_rows(cursor):
    store.insert_agent(cursor, 3, 'login.one', 'hash', 'First', 'Last', 'e@x', '1', 'L', 'master', 't')
    row = store.get_active_agent_for_login(cursor, 'login.one')
    assert row == (3, 'login.one', 'First', 'hash', 'master', 'Last', 'e@x', '1', 'L')
    assert store.get_active_agent_for_login(cursor, 'LOGIN.ONE') is None
    assert store.get_agent_password_row(cursor, 3) == ('hash', 'login.one', 'First', 'Last') and store.get_agent_password_row(cursor, 4) is None
    store.set_agent_password_hash(cursor, 3, 'new', 'stamp')
    store.update_agent_contact(cursor, 3, 'n@x', '2', 'L2', 'stamp2')
    assert cursor.execute('SELECT password_hash, email, phone, license, updated_at FROM agents_v2 WHERE id=3').fetchone() == ('new', 'n@x', '2', 'L2', 'stamp2')
    cursor.execute('UPDATE agents_v2 SET is_active=0')
    assert store.get_active_agent_for_login(cursor, 'login.one') is None
