"""S4.7 / package 2: characterization of every DB Shell endpoint (`/crm/dbshell*`) and of the dashboard routes next to it.

Observed through HTTP with the real login (`crm_env`): access checks, the unlock/lock cycle, table listing and data, cell edits,
orphan folders, duplicates and text replacement - responses, status codes and resulting data. Written and passing on the OLD code;
must pass unchanged after the DB Shell moves from `routes/dashboard.py` to `routes/dbshell.py`.
"""
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
SECRET = 'unlock-me-123'


@pytest.fixture()
def shell(app, crm_env, crm_login, monkeypatch):
    monkeypatch.setenv('DB_SHELL_PASSWORD', SECRET)
    master = crm_login(app, CRM_MASTER)
    return master


@pytest.fixture()
def open_shell(shell):
    assert shell.post('/crm/dbshell/unlock', json={'password': SECRET}).get_json() == {'success': True}
    return shell


def agents_q(sql, *params):
    conn = sqlite3.connect(storage_paths.agents_db_path())
    try:
        return conn.execute(sql, params).fetchall()
    finally:
        conn.close()


# ------------------------------------------------------------------------------------------------------------ access
def test_status_unlock_and_lock_cycle(shell):
    body = shell.get('/crm/dbshell/status').get_json()
    assert body == {'unlocked': False, 'is_master': True, 'default_db': 'idb', 'databases': [{'key': 'idb', 'label': 'IDB.db'}, {'key': 'agents', 'label': 'agents.db'}]}
    wrong = shell.post('/crm/dbshell/unlock', json={'password': 'nope'})
    assert wrong.status_code == 401 and wrong.get_json() == {'success': False, 'error': 'Nieprawidłowe hasło.'}
    assert shell.post('/crm/dbshell/unlock', json={'password': SECRET}).get_json() == {'success': True}
    assert shell.get('/crm/dbshell/status').get_json()['unlocked'] is True
    assert shell.post('/crm/dbshell/lock').get_json() == {'success': True} and shell.get('/crm/dbshell/status').get_json()['unlocked'] is False


def test_unlock_is_disabled_without_a_configured_password(shell, monkeypatch):
    monkeypatch.setenv('DB_SHELL_PASSWORD', '')
    response = shell.post('/crm/dbshell/unlock', json={'password': ''})
    assert response.status_code == 503 and response.get_json() == {'success': False, 'error': 'DB Shell jest wyłączony (brak konfiguracji hasła).'}


@pytest.mark.parametrize('method, path', [('get', '/crm/dbshell/status'), ('post', '/crm/dbshell/unlock'), ('post', '/crm/dbshell/lock'),
                                         ('get', '/crm/dbshell/tables'), ('get', '/crm/dbshell/table/estatedata'), ('post', '/crm/dbshell/cell'),
                                         ('get', '/crm/dbshell/orphan-offer-folders'), ('delete', '/crm/dbshell/orphan-offer-folders/5'),
                                         ('post', '/crm/dbshell/duplicates'), ('post', '/crm/dbshell/replace-text')])
def test_an_ordinary_agent_gets_403_everywhere(app, crm_env, crm_login, method, path):
    ann = crm_login(app, CRM_ANN)
    response = getattr(ann, method)(path, json={})
    assert response.status_code == 403 and response.get_json() == {'error': 'Brak uprawnień.'}


@pytest.mark.parametrize('method, path', [('get', '/crm/dbshell/tables'), ('get', '/crm/dbshell/table/estatedata'), ('post', '/crm/dbshell/cell'),
                                         ('get', '/crm/dbshell/orphan-offer-folders'), ('delete', '/crm/dbshell/orphan-offer-folders/5'),
                                         ('post', '/crm/dbshell/duplicates'), ('post', '/crm/dbshell/replace-text')])
def test_a_locked_shell_answers_401_to_the_master(shell, method, path):
    response = getattr(shell, method)(path, json={})
    assert response.status_code == 401 and response.get_json() == {'error': 'DB Shell jest zablokowany.'}


def test_the_ui_page_is_master_only(app, crm_env, crm_login, shell):
    assert shell.get('/crm/dbshell-ui').status_code == 200
    ann = crm_login(app, CRM_ANN)
    response = ann.get('/crm/dbshell-ui')
    assert response.status_code == 302 and response.headers['Location'].endswith('/crm/dashboard')
    assert ann.get('/crm/dashboard?panel=dbshell').status_code == 403
    assert shell.get('/crm/dashboard?panel=dbshell').status_code == 200


# ------------------------------------------------------------------------------------------------------------ tables and data
def test_tables_of_both_databases_and_the_default_for_an_unknown_key(open_shell):
    assert open_shell.get('/crm/dbshell/tables').get_json() == {'tables': ['estatedata'], 'db': 'idb'}
    agents = open_shell.get('/crm/dbshell/tables?db=agents').get_json()
    assert agents == {'tables': ['agent_branches_v2', 'agent_roles_v2', 'agents_v2', 'branches_v2', 'roles_v2'], 'db': 'agents'}
    assert open_shell.get('/crm/dbshell/tables?db=bogus').get_json() == {'tables': ['estatedata'], 'db': 'idb'}
    assert open_shell.get('/crm/dbshell/tables?db=AGENTS%20').get_json()['db'] == 'agents'


def test_table_data_shape_limits_and_errors(open_shell):
    body = open_shell.get('/crm/dbshell/table/agents_v2?db=agents&limit=2').get_json()
    assert body['table'] == 'agents_v2' and body['db'] == 'agents' and body['pk_columns'] == ['id'] and len(body['rows']) == 2
    assert body['columns'][:3] == ['id', 'login', 'password_hash'] and set(body['rows'][0]) == {'_rowid', *body['columns']}
    assert [r['id'] for r in body['rows']] == [101, 102]
    assert len(open_shell.get('/crm/dbshell/table/agents_v2?db=agents&limit=0').get_json()['rows']) == 1          # limit is clamped to 1..1000
    assert len(open_shell.get('/crm/dbshell/table/agents_v2?db=agents&limit=abc').get_json()['rows']) == 3         # bad limit -> 200 default
    missing = open_shell.get('/crm/dbshell/table/nope?db=agents')
    assert missing.status_code == 404 and missing.get_json() == {'error': 'Tabela nie istnieje.'}
    idb = open_shell.get('/crm/dbshell/table/estatedata').get_json()
    assert idb['db'] == 'idb' and [r['ID'] for r in idb['rows']] == [501, 601] and idb['pk_columns'] == ['ID']


# ------------------------------------------------------------------------------------------------------------ cell edit
def cell(shell, **body):
    return shell.post('/crm/dbshell/cell', json={'db': 'agents', **body})


def test_cell_update_and_its_validation(open_shell):
    ok = cell(open_shell, table='agents_v2', column='phone', rowid=102, value='123')
    assert ok.status_code == 200 and ok.get_json() == {'success': True}
    assert agents_q('SELECT phone FROM agents_v2 WHERE rowid=102') == [('123',)]
    assert cell(open_shell, table='agents_v2', column='phone', rowid=102, value=None).get_json() == {'success': True}
    assert agents_q('SELECT phone FROM agents_v2 WHERE rowid=102') == [(None,)]
    assert cell(open_shell, table='', column='phone', rowid=102).get_json() == {'error': 'Brak wymaganych danych.'}
    assert cell(open_shell, table='agents_v2', column='phone').status_code == 400
    assert cell(open_shell, table='agents_v2', column='_rowid', rowid=1, value='x').get_json() == {'error': 'Nie można edytować _rowid.'}
    assert cell(open_shell, table='agents_v2', column='phone', rowid='abc').get_json() == {'error': 'Nieprawidłowy rowid.'}
    for body, message in (({'table': 'nope', 'column': 'phone', 'rowid': 1}, 'Tabela nie istnieje.'), ({'table': 'agents_v2', 'column': 'nope', 'rowid': 1}, 'Kolumna nie istnieje.'),
                          ({'table': 'agents_v2', 'column': 'phone', 'rowid': 999}, 'Nie znaleziono wiersza do aktualizacji.')):
        response = cell(open_shell, value='x', **body)
        assert response.status_code == 404 and response.get_json() == {'error': message}


def test_cell_update_treats_names_as_identifiers_never_as_sql(open_shell):
    response = cell(open_shell, table='agents_v2"; DROP TABLE agents_v2; --', column='phone', rowid=1, value='x')
    assert response.status_code == 404 and agents_q('SELECT COUNT(*) FROM agents_v2') == [(3,)]
    assert cell(open_shell, table='agents_v2', column='phone"--', rowid=1, value='x').status_code == 404


# ------------------------------------------------------------------------------------------------------------ orphan folders
def make_offer_folder(root, offer_id, *, images=0, description=None):
    folder = root / 'offers' / str(offer_id)
    folder.mkdir(parents=True)
    for index in range(images):
        (folder / f'image_{offer_id}_url_{index}.jpg').write_bytes(b'x')
    if description is not None:
        (folder / f'description_{offer_id}.md').write_text(description, encoding='utf-8')
    return folder


def test_orphan_folders_report_orphans_and_incomplete_offers(open_shell, crm_env):
    make_offer_folder(crm_env, 501, images=2, description='Opis')              # complete offer
    make_offer_folder(crm_env, 700, images=1, description='x')                  # orphan with an image and a description
    (crm_env / 'offers' / '700' / 'docs').mkdir()
    make_offer_folder(crm_env, 30)                                              # orphan, empty
    (crm_env / 'offers' / 'notes').mkdir()                                      # not numeric: ignored
    (crm_env / 'offers' / '99.txt').write_text('x')
    body = open_shell.get('/crm/dbshell/orphan-offer-folders').get_json()
    assert body['db'] == 'idb' and body['count'] == 2 and body['incomplete_count'] == 1
    assert body['orphans'] == [{'folder_id': 30, 'image_files': 0, 'has_description': False, 'has_docs': False},
                               {'folder_id': 700, 'image_files': 1, 'has_description': True, 'has_docs': True}]
    assert body['incomplete_offers'] == [{'offer_id': 601, 'image_files': 0, 'has_description_file': False, 'description_empty': True}]


def test_orphan_folders_of_a_whitespace_description_are_incomplete(open_shell, crm_env):
    make_offer_folder(crm_env, 501, images=1, description='   \n')
    make_offer_folder(crm_env, 601, images=1, description='ok')
    body = open_shell.get('/crm/dbshell/orphan-offer-folders').get_json()
    assert body['incomplete_offers'] == [{'offer_id': 501, 'image_files': 1, 'has_description_file': True, 'description_empty': True}]


def test_orphan_folders_for_another_database_return_the_note(open_shell):
    body = open_shell.get('/crm/dbshell/orphan-offer-folders?db=agents').get_json()
    assert body == {'db': 'agents', 'orphans': [], 'incomplete_offers': [], 'count': 0, 'incomplete_count': 0,
                    'note': 'Sprawdzanie folderow ofert dotyczy tylko bazy IDB.db.'}


def test_deleting_an_orphan_folder(open_shell, crm_env):
    existing = make_offer_folder(crm_env, 501, images=1)
    orphan = make_offer_folder(crm_env, 700, images=1)
    assert open_shell.delete('/crm/dbshell/orphan-offer-folders/501').status_code == 409
    assert open_shell.delete('/crm/dbshell/orphan-offer-folders/501').get_json() == {'error': 'Ten folder ma odpowiadajaca oferte w bazie i nie moze byc usuniety.'}
    assert existing.is_dir()
    assert open_shell.delete('/crm/dbshell/orphan-offer-folders/888').get_json() == {'error': 'Folder nie istnieje.'}
    assert open_shell.delete('/crm/dbshell/orphan-offer-folders/700?db=agents').get_json() == {'error': 'Usuwanie folderow ofert dotyczy tylko bazy IDB.db.'}
    assert orphan.is_dir()
    done = open_shell.delete('/crm/dbshell/orphan-offer-folders/700')
    assert done.status_code == 200 and done.get_json() == {'success': True, 'folder_id': 700} and not orphan.exists()


# ------------------------------------------------------------------------------------------------------------ duplicates
def duplicates(shell, **body):
    return shell.post('/crm/dbshell/duplicates', json={'db': 'agents', **body})


def test_duplicates_validation_and_results(open_shell):
    assert duplicates(open_shell, table='').get_json() == {'error': 'Brak nazwy tabeli.'}
    assert duplicates(open_shell, table='agents_v2', columns=[]).get_json() == {'error': 'Wybierz przynajmniej jedną kolumnę.'}
    assert duplicates(open_shell, table='nope', columns=['a']).status_code == 404
    bad = duplicates(open_shell, table='agents_v2', columns=['last_name', 'zzz', 'yyy'])
    assert bad.status_code == 400 and bad.get_json() == {'error': 'Nieprawidłowe kolumny: zzz, yyy'}
    body = duplicates(open_shell, table='agents_v2', columns=['last_name', 'last_name', ' ']).get_json()
    assert body == {'success': True, 'db': 'agents', 'table': 'agents_v2', 'columns': ['last_name'], 'rows': [
        {'values': {'last_name': 'Test'}, 'duplicate_count': 3, 'rowids': [101, 102, 103]}], 'groups': 1, 'rows_total': 3, 'ignore_empty': True, 'limit': 50}
    conn = sqlite3.connect(storage_paths.agents_db_path())
    conn.execute("UPDATE agents_v2 SET phone=''")
    conn.commit()
    conn.close()
    assert duplicates(open_shell, table='agents_v2', columns=['phone']).get_json()['groups'] == 0                    # empty values ignored by default
    empty = duplicates(open_shell, table='agents_v2', columns=['phone'], ignore_empty=False, limit=0).get_json()
    assert empty['groups'] == 1 and empty['rows_total'] == 3 and empty['limit'] == 1 and empty['ignore_empty'] is False


# ------------------------------------------------------------------------------------------------------------ replace text
def replace(shell, **body):
    return shell.post('/crm/dbshell/replace-text', json={'db': 'agents', **body})


def test_replace_text_validation_and_effect(open_shell):
    assert replace(open_shell, table='', column='x', find='a').get_json() == {'error': 'Brak nazwy tabeli.'}
    assert replace(open_shell, table='agents_v2', column='', find='a').get_json() == {'error': 'Brak nazwy kolumny.'}
    assert replace(open_shell, table='agents_v2', column='first_name', find='').get_json() == {'error': 'Podaj tekst do wyszukania.'}
    assert replace(open_shell, table='agents_v2', column='first_name', find=None).status_code == 400
    assert replace(open_shell, table='nope', column='first_name', find='a').status_code == 404
    assert replace(open_shell, table='agents_v2', column='nope', find='a').get_json() == {'error': 'Kolumna nie istnieje.'}
    body = replace(open_shell, table='agents_v2', column='last_name', find='es', replace='ES').get_json()
    assert body == {'success': True, 'db': 'agents', 'table': 'agents_v2', 'column': 'last_name', 'find': 'es', 'replace': 'ES', 'updated_rows': 3}
    assert agents_q('SELECT DISTINCT last_name FROM agents_v2') == [('TESt',)]
    assert replace(open_shell, table='agents_v2', column='last_name', find='zzz', replace=None).get_json()['updated_rows'] == 0
    same = replace(open_shell, table='agents_v2', column='last_name', find='TES', replace='TES').get_json()
    assert same['updated_rows'] == 3 and same['replace'] == 'TES'


def test_dashboard_routes_next_to_the_shell(app, crm_env, crm_login):
    ann = crm_login(app, CRM_ANN)
    assert ann.get('/crm/dashboard').status_code == 200
    assert ann.get('/crm/dashboard?panel=export-jobs').status_code == 403
    assert ann.post('/crm/upload_avatar').status_code == 302
