"""Grouped read projection: actual queue and receiver, synthetic databases only."""
import copy
import json

import pytest

from tests.investmentmanager.test_domestic_packages import data_root, isolated, sql
from tests.investmentmanager.test_sync_tasks import country, foreign_root
from tests.investmentmanager.test_sync_task_contract import consumer
from InvestmentManager.integrator import sync_tasks as queue
from InvestmentManager import export_handoff as server


def request(**kwargs):
    return dict(operation='list_sync_offers',offset=0,limit=20,categories=[],portals=[],snapshot=None)|kwargs


def read(consumer,**kwargs):
    body=request(**kwargs);value=server.dispatch_request(body)
    assert value['ok'],value
    return consumer.validate_offers_page(value,body)


def test_all_portals_one_offer_and_old_task_api_is_preserved(consumer,country):
    old=queue.list_tasks()
    view=read(consumer)
    assert old['total']==4 and view['total']==view['offer_count']==1
    group=view['items'][0]
    assert group['key']=='domestic:offer:17' and len(group['tasks'])==4
    assert group['tasks']==old['items'] and view['counts']==old['counts']
    assert all(not state['present'] and state['is_published'] is None for state in group['crm'].values())
    assert set(queue.list_tasks())==set(old)


def test_groups_before_pagination_and_filters_keep_whole_offer(consumer,country):
    sql(country,"INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,updated_at) VALUES(17,'domiporta',1,1,'test')")
    sql(country,"INSERT INTO EstateData(ID,Status_oferty,Typ_nieruchomosci,Tytul) VALUES('18','aktywna','dom','Second offer')")
    old=queue.list_tasks(limit=2)
    assert any(row['subject']['id']==17 for row in old['items'])
    first=read(consumer,limit=1)
    assert len(first['items'][0]['tasks'])==4 and first['total']==2
    second=read(consumer,offset=1,limit=1,snapshot=first['snapshot'])
    assert second['items'][0]['subject']['id']==18 and len(second['items'][0]['tasks'])==3
    chosen=read(consumer,categories=['update'],portals=['domiporta'])
    assert chosen['total']==1 and len(chosen['items'][0]['tasks'])==4
    assert {r['category'] for r in chosen['items'][0]['tasks']}=={'new','update'}
    assert read(consumer,categories=['update'],portals=['no'])['total']==0


def test_crm_row_presence_changes_snapshot_even_when_category_stays_new(consumer,country):
    before=read(consumer)
    sql(country,"INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,updated_at) VALUES(17,'no',0,0,'test')")
    reply=server.dispatch_request(request(snapshot=before['snapshot']))
    assert reply=={'view_version':1,'ok':False,'error':'snapshot_changed'}
    after=read(consumer)
    assert after['snapshot']!=before['snapshot'] and after['counts']==before['counts']
    assert after['items'][0]['crm']['no']==dict(present=True,valid=True,is_published=0,needs_update=0)


def test_snapshot_ignores_only_ephemeral_verification_time(consumer,country,monkeypatch):
    rows=queue.list_tasks()['items'];stamp=['2026-11-01T00:00:00Z'];state=['READY']
    def collect(root,settings):
        result=copy.deepcopy(rows)
        result[0]['package']=dict(package_id='a'*32,state=state[0],prepared_at='2026-11-01T00:00:00Z',checked_at=stamp[0])
        return result
    monkeypatch.setattr(queue,'_collect_tasks',collect)
    first=read(consumer)
    stamp[0]='2026-11-01T01:00:00Z'
    assert read(consumer,snapshot=first['snapshot'])['snapshot']==first['snapshot']
    state[0]='STALE'
    assert server.dispatch_request(request(snapshot=first['snapshot']))['error']=='snapshot_changed'


def test_project_separate_once_with_member_crm_and_individual_offer_tasks(consumer,foreign_root):
    root,settings,_=foreign_root
    sql(root,"UPDATE foreign_offer_portal_sync SET is_published=0 WHERE foreign_offer_id=11",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')
    # Direct API allows the synthetic media pin settings; validation uses the
    # exact same response as SSH, without opening connections.
    first=queue.list_offers(limit=1,settings=settings)
    collected=[]
    for offset in range(first['total']):
        body=request(offset=offset,limit=1,snapshot=first['snapshot'])
        value=queue.list_offers(**{k:body[k] for k in ('offset','limit','categories','portals','snapshot')},settings=settings)
        consumer.validate_offers_page(value,body);collected+=value['items']
    assert len({g['key'] for g in collected})==len(collected)
    positions={g['key']:i for i,g in enumerate(collected)}
    for group in collected:
        for ref in group['project_refs']:
            assert ref['page_offset']==positions[ref['project_key']]
        for member in group['members']:
            assert member['page_offset']==positions[f"foreign:offer:{member['offer_id']}"]
    project=next(g for g in collected if g['key']=='foreign:project:7')
    assert project['title']=='Azure Bay' and project['offer_ids']==[11,13] and len(project['tasks'])==1
    members={m['offer_id']:m for m in project['members']}
    assert members[11]['crm']['is_published']==0 and members[13]['crm']['is_published']==1
    own=next(g for g in collected if g['key']=='foreign:offer:11')
    assert len(own['tasks'])==1 and own['tasks'][0]['portal']=='domiporta'
    assert len(own['project_refs'])==1 and own['project_refs'][0]['key']==project['tasks'][0]['key']
    keys=[task['key'] for g in collected for task in g['tasks']]
    assert len(keys)==len(set(keys))
    original=queue.list_tasks(settings=settings)
    assert set(keys)=={row['key'] for row in original['items']}
    selected=queue.list_offers(categories=['update'],portals=['tabelaofert'],settings=settings)
    assert {g['key'] for g in selected['items']}=={'foreign:offer:11','foreign:offer:13','foreign:project:7'}
    projects=queue.list_offers(domains=['foreign'],subject_kinds=['cyprus_development'],settings=settings)
    assert projects['total']==1 and projects['items'][0]['key']=='foreign:project:7'


def test_orphan_otodom_kept_as_readonly_error_group(consumer,country):
    sql(country,"INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,updated_at) VALUES(999,'otodom',1,'test')")
    group=next(g for g in read(consumer)['items'] if g['subject']['id']==999)
    assert not group['source_exists'] and group['title']=='' and group['crm']['otodom']['is_published']==1
    assert group['activity']=='unknown'
    assert group['tasks'][0]['send_allowed'] is False and group['tasks'][0]['package'] is None


@pytest.mark.parametrize('domain,value,expected',[
    ('domestic','aktywna','active'),('domestic',' Aktywna ','active'),
    ('domestic','Nieaktywna','inactive'),('domestic',None,'unknown'),
    ('domestic','other','unknown'),('foreign',1,'active'),('foreign',0,'inactive'),
    ('foreign',None,'unknown'),('foreign',2,'unknown'),('foreign','1','unknown'),
    ('foreign',True,'unknown'),
])
def test_activity_projection_only_recognizes_existing_crm_values(domain,value,expected):
    assert queue._activity(domain,value)==expected


def test_activity_is_read_from_crm_and_inactive_can_require_withdrawal(consumer,country):
    before=read(consumer)
    assert before['items'][0]['activity']=='active'
    sql(country,"INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,updated_at) VALUES(17,'no',1,0,'test')")
    sql(country,"UPDATE EstateData SET Status_oferty='Nieaktywna'")
    result=read(consumer)
    group=result['items'][0]
    assert group['activity']=='inactive'
    assert group['tasks'][0]['category']=='withdraw'
    assert queue.list_tasks()['items']==group['tasks']


def test_foreign_offer_activity_is_independent_of_portal_status(consumer,foreign_root):
    root,settings,_=foreign_root
    sql(root,"UPDATE foreign_offer_portal_sync SET needs_update=1",db='foreign_offers.db')
    sql(root,"UPDATE foreign_offers SET is_active=0 WHERE id=13",db='foreign_offers.db')
    value=queue.list_offers(settings=settings)
    consumer.validate_offers_page(value,request())
    groups={g['key']:g for g in value['items']}
    assert groups['foreign:offer:11']['activity']=='active'
    assert groups['foreign:offer:13']['activity']=='inactive'
    assert groups['foreign:project:7']['activity']=='unknown'


@pytest.mark.parametrize('change',[
    {'offset':True},{'limit':21},{'limit':0},{'categories':['other']},
    {'categories':['new','new']},{'portals':['unknown']},{'snapshot':'bad'},{'extra':'no'},
])
def test_rpc_strict_schema(country,change):
    assert server.dispatch_request(request(**change))=={'view_version':1,'ok':False,'error':'invalid_request'}


def test_projection_is_readonly_and_does_not_change_original_task_fields(consumer,country):
    before={p:p.read_bytes() for p in (country/'databases').glob('*.db')}
    old=queue.list_tasks()
    read(consumer)
    assert {p:p.read_bytes() for p in before}==before
    assert queue.list_tasks()['items']==old['items']


def test_response_limit_returns_safe_error(country,monkeypatch):
    # Bound remains 1 MiB. A very large project is never silently truncated.
    original=queue._group_tasks
    def huge(rows,context):
        groups=original(rows,context);groups[0]['title']='x'*(1024*1024);return groups
    monkeypatch.setattr(queue,'_group_tasks',huge)
    assert server.dispatch_request(request())=={'view_version':1,'ok':False,'error':'response_limit'}
