"""Real agent mutation paths on disposable foreign CRM; no live transport."""
from contextlib import closing
import sqlite3
import socket

import pytest
from flask import Flask
from tests.investmentmanager.test_foreign_packages_v2 import foreign_root
from tests.investmentmanager.test_domestic_export_invalidation import agent_form, call_agent
from InvestmentManager.integrator import foreign_consistency as consistency
from InvestmentManager.integrator import foreign_packages as packages, export_attempts as attempts, sync_tasks


@pytest.fixture
def crm(foreign_root, monkeypatch):
    root, settings, _ = foreign_root
    def forbidden(*a, **k):
        raise AssertionError('Live network forbidden')
    monkeypatch.setattr(socket.socket, 'connect', forbidden)
    monkeypatch.setattr(socket, 'create_connection', forbidden)
    with closing(sqlite3.connect(root/'databases/agents.db')) as c,c:
        c.executescript('ALTER TABLE agents_v2 ADD COLUMN updated_at TEXT; CREATE TABLE agent_roles_v2(agent_id,role_id,created_at); CREATE TABLE agent_branches_v2(agent_id,branch_id,is_primary,created_at);')
        row=list(c.execute('SELECT * FROM agents_v2 WHERE id=7').fetchone());row[0]=8
        c.execute('INSERT INTO agents_v2 VALUES ('+','.join('?' for _ in row)+')',row)
    with closing(sqlite3.connect(root/'databases/foreign_offers.db')) as c,c:
        c.execute("UPDATE foreign_offers SET agent_identifier='8',agent_name='',agent_email='',agent_phone=''")
        c.execute("UPDATE foreign_offers SET agent_identifier='7' WHERE id=11")
    app=Flask('foreign-invalidation');app.secret_key='synthetic'
    return app,root,settings


def flags(root):
    with closing(sqlite3.connect(root/'databases/foreign_offers.db')) as c:
        return c.execute('SELECT foreign_offer_id,portal_key,is_published,needs_update FROM foreign_offer_portal_sync ORDER BY foreign_offer_id,portal_key').fetchall()


@pytest.mark.parametrize('field,value', [('access_level','master'),('licencja','999')])
def test_nonexported_agent_change_preserves_foreign_publications(crm,field,value):
    app,root,_=crm;before=flags(root)
    form=agent_form();form[field]=value;call_agent(app,form)
    assert flags(root)==before


@pytest.mark.parametrize('override', [False,True])
def test_contact_invalidates_only_actual_offer_portal_projection(crm,override):
    app,root,_=crm
    if override:
        with closing(sqlite3.connect(root/'databases/foreign_offers.db')) as c,c:
            c.execute("UPDATE foreign_offers SET agent_phone='777' WHERE id=11")
    before=flags(root);form=agent_form();form['telefon']='555';call_agent(app,form)
    after=flags(root)
    assert [r[:3] for r in after]==[r[:3] for r in before]
    assert {(r[0],r[1]) for r in after if r[3]}==(set() if override else {(11,'domiporta'),(11,'tabelaofert')})


def test_agent_revision_stales_package_but_does_not_requalify_unchanged_publication(crm):
    app,root,settings=crm
    package=packages.prepare_package('foreign_offer',11,'domiporta','add',settings=settings)
    attempt=attempts.create_attempt(package['package_id'],subject={'kind':'foreign_offer','id':11},
                                    portal='domiporta',action='add',domain='foreign',settings=settings)
    attempts.start_transport(attempt['attempt_id'],attempt['binding'],domain='foreign',settings=settings)
    attempts.record_transport_result(attempt['attempt_id'],attempt['binding'],'confirmed',domain='foreign')
    assert attempts.acknowledge_attempt(attempt['attempt_id'],attempt['binding'],domain='foreign',settings=settings)['state']=='ack_completed'
    before=flags(root)
    with closing(sqlite3.connect(root/'databases/foreign_offers.db')) as c:
        history=c.execute("SELECT * FROM foreign_offer_portal_sync_events WHERE event_type='export_attempt_v2'").fetchall()
        revision=consistency.revision(c)
    form=agent_form();form['licencja']='999';call_agent(app,form)
    assert flags(root)==before
    with closing(sqlite3.connect(root/'databases/foreign_offers.db')) as c:
        assert consistency.revision(c)!=revision
        assert c.execute("SELECT * FROM foreign_offer_portal_sync_events WHERE event_type='export_attempt_v2'").fetchall()==history
    assert packages.verify_package(package['package_id'],settings=settings)['state']=='STALE'
    assert not any(u['subject']=={'kind':'foreign_offer','id':11} and u['portal']=='domiporta' for u in sync_tasks.qualify_foreign_units(root))
    # An actual exported contact change still creates the appropriate update.
    form['telefon']='555';call_agent(app,form)
    units=sync_tasks.qualify_foreign_units(root)
    assert any(u['subject']=={'kind':'foreign_offer','id':11} and u['portal']=='domiporta' and u['category']=='update' for u in units)


def test_foreign_empty_email_layout_never_exports_access_level():
    from InvestmentManager.export_engine.foreign_offers_export import _extract_agent_contact_fields
    assert _extract_agent_contact_fields([7,'login','hash','master','Jan','Testowy','','555','L1'])=={'full_name':'Jan Testowy','email':'','phone':'555'}
