"""Characterize existing CRM/queue semantics; do not approve or change mapping."""
from contextlib import closing
import json
from pathlib import Path
import shutil
import sqlite3
import subprocess

import pytest

from tests.investmentmanager.test_domestic_packages import data_root, isolated, sql
from tests.investmentmanager.test_sync_tasks import country, foreign_root, completed
from InvestmentManager.integrator import sync_tasks as queue, domestic_sets as sets, export_attempts as attempts
from InvestmentManager.integrator.portal_sync_state import set_offer_portal_sync_state as set_state
from InvestmentManager.routes.offer_catalog import _fetch_portal_sync_map


def status(root, portal='no'):
    with closing(sqlite3.connect(root/'databases/IDB.db')) as conn:
        return _fetch_portal_sync_map(conn,[17]).get(17,{}).get(portal)


def task(portal='no',**kwargs):
    return next((row for row in queue.list_tasks(**kwargs)['items'] if row['domain']=='domestic' and row['portal']==portal),None)


@pytest.mark.parametrize('state,expected,published',[
    ('no_info','new',False),('unpublished','new',False),
    ('published',None,True),('update_required','update',True),
])
def test_manual_crm_states_without_export_history(country,state,expected,published):
    set_state(offer_id=17,portal_key='no',state=state)
    with closing(sqlite3.connect(country/'databases/IDB.db')) as conn:
        assert conn.execute("SELECT COUNT(*) FROM offer_portal_sync_events WHERE event_type='export_attempt_v1'").fetchone()[0]==0
    current=status(country);row=task()
    if state=='no_info':assert current is None
    else:assert bool(current['is_published'])==published
    if expected is None:assert row is None
    else:assert row['category']==expected and row['published']==published


def test_portal_states_are_independent_and_missing_new_history_is_not_unpublished(country):
    for portal,state in [('no','published'),('domiporta','update_required'),('tabelaofert','unpublished'),('gruntguru','published')]:
        set_state(offer_id=17,portal_key=portal,state=state)
    before=(country/'databases/IDB.db').read_bytes()
    rows=queue.list_tasks()['items']
    assert {(row['portal'],row['category']) for row in rows}=={('domiporta','update'),('tabelaofert','new')}
    assert (country/'databases/IDB.db').read_bytes()==before


def test_generation_and_verification_do_not_reset_crm_publications(country):
    for portal in sets.PORTALS:set_state(offer_id=17,portal_key=portal,state='published')
    before=(country/'databases/IDB.db').read_bytes()
    assert sets.prepare_set(17,'add')['replaced']
    assert sets.verify_set(17,'add')['state']=='READY'
    assert (country/'databases/IDB.db').read_bytes()==before
    assert queue.list_tasks()['items']==[]


@pytest.mark.parametrize('action',['add','delete'])
def test_start_and_transport_result_keep_state_until_ack(country,action):
    set_state(offer_id=17,portal_key='no',state='unpublished' if action=='add' else 'published')
    if action=='delete':sql(country,"UPDATE EstateData SET Status_oferty='nieaktywna'")
    assert sets.prepare_set(17,action)['replaced']
    pointer=sets.current(country/'exports/domestic',17,action)
    before=status(country)
    item=attempts.create_attempt(package_id=pointer['packages']['no'],offer_id=17,portal='no',action=action)
    assert status(country)==before
    attempts.start_transport(item['attempt_id'],item['binding'])
    assert status(country)==before
    attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
    assert status(country)==before
    assert attempts.acknowledge_attempt(item['attempt_id'],item['binding'])['state']=='ack_completed'
    assert status(country)['is_published']==int(action=='add') and status(country)['needs_update']==0
    assert status(country,'domiporta') is None


def test_manual_published_can_still_be_update_due_to_older_ack_fingerprint(country):
    # This discrepancy is characterized for approval; no automatic reconciliation.
    assert sets.prepare_set(17,'add')['replaced'];completed(country,'no')
    sql(country,"UPDATE EstateData SET Cena='345678'")
    set_state(offer_id=17,portal_key='no',state='published')
    assert status(country)['is_published']==1 and status(country)['needs_update']==0
    row=task()
    assert row['category']=='update' and row['published'] is True


def test_ack_cannot_overwrite_newer_manual_crm_state(country):
    set_state(offer_id=17,portal_key='no',state='unpublished')
    assert sets.prepare_set(17,'add')['replaced']
    pointer=sets.current(country/'exports/domestic',17,'add')
    item=attempts.create_attempt(package_id=pointer['packages']['no'],offer_id=17,portal='no',action='add')
    attempts.start_transport(item['attempt_id'],item['binding'])
    set_state(offer_id=17,portal_key='no',state='update_required')
    before=status(country)
    attempts.record_transport_result(item['attempt_id'],item['binding'],'confirmed')
    assert attempts.acknowledge_attempt(item['attempt_id'],item['binding'])['state']=='ack_rejected'
    assert status(country)==before and before['is_published']==1 and before['needs_update']==1


def test_manual_published_does_not_clear_old_error_on_existing_row(country):
    set_state(offer_id=17,portal_key='no',state='unpublished')
    sql(country,"UPDATE offer_portal_sync SET last_error='synthetic legacy error' WHERE portal_key='no'")
    set_state(offer_id=17,portal_key='no',state='published')
    assert status(country)['is_published']==1 and status(country)['needs_update']==0
    assert status(country)['last_error']=='synthetic legacy error'
    row=task()
    assert row['category']=='error' and row['published'] is True and not row['send_allowed']


def test_real_badge_function_distinguishes_unknown_from_unpublished(country):
    node=shutil.which('node')
    if not node:pytest.skip('Node unavailable')
    source=Path(__file__).resolve().parents[2]/'InvestmentManager/static/js/offers_cards.js'
    harness="""const fs=require('fs'),vm=require('vm');const src=fs.readFileSync(process.argv[1],'utf8');
    const start=src.indexOf('function getPortalSyncBadgeMeta('),end=src.indexOf('function isPlotOffer(',start);
    const ctx={};vm.createContext(ctx);vm.runInContext(src.slice(start,end),ctx);
    console.log(JSON.stringify([null,{is_published:0,needs_update:0},{is_published:1,needs_update:0},
      {is_published:1,needs_update:1},{is_published:0,needs_update:1}].map(ctx.getPortalSyncBadgeMeta)));"""
    process=subprocess.run([node,'-e',harness,str(source)],capture_output=True,text=True,encoding='utf8',check=True)
    values=json.loads(process.stdout)
    assert [value['state'] for value in values]==['no_info','unpublished','published','update_required','update_required']
    assert [value['text'] for value in values]==['Brak danych','Nieopublikowana','Dodana','Wymaga aktualizacji','Wymaga aktualizacji']


def test_catalog_portal_status_badges_are_read_only():
    source=(Path(__file__).resolve().parents[2]/'InvestmentManager/static/js/offers_cards.js').read_text(encoding='utf-8')
    assert '/crm/offers/portal-sync/' not in source
    assert 'cyclePortalSyncState' not in source
    assert "document.createElement('span')" in source


def test_dirty_unpublished_flags_have_different_badge_and_queue_meanings(country):
    set_state(offer_id=17,portal_key='no',state='unpublished')
    sql(country,"UPDATE offer_portal_sync SET needs_update=1 WHERE portal_key='no'")
    assert status(country)['is_published']==0 and status(country)['needs_update']==1
    assert task()['category']=='new'  # existing behavior, not a proposed policy


def test_foreign_published_states_do_not_need_new_ack_history(foreign_root):
    root,settings,_=foreign_root
    assert not [row for row in queue.list_tasks(settings=settings)['items'] if row['domain']=='foreign' and row['action']=='add']
    sql(root,"UPDATE foreign_offer_portal_sync SET needs_update=1 WHERE foreign_offer_id=11 AND portal_key='domiporta'",db='foreign_offers.db')
    rows=[row for row in queue.list_tasks(settings=settings)['items'] if row['domain']=='foreign' and row['action']=='add']
    assert len(rows)==1 and rows[0]['portal']=='domiporta' and rows[0]['category']=='update' and rows[0]['published']


def test_foreign_group_boolean_does_not_describe_each_members_crm_state(foreign_root):
    root,settings,_=foreign_root
    sql(root,"UPDATE foreign_offer_portal_sync SET is_published=0 WHERE foreign_offer_id=11 AND portal_key='tabelaofert'",db='foreign_offers.db')
    sql(root,"UPDATE foreign_offer_portal_sync SET needs_update=1 WHERE foreign_offer_id=13 AND portal_key='tabelaofert'",db='foreign_offers.db')
    row=next(row for row in queue.list_tasks(settings=settings)['items'] if row['domain']=='foreign' and row['portal']=='tabelaofert' and row['action']=='add')
    assert row['offer_ids']==[11,13] and row['category']=='update'
    assert row['published'] is False  # inherited from first member, not a per-member map
