"""Synthetic queue datasets for characterization and differential qualification tests.

Attempts are written directly as events (the real history parser validates them), so
thousands of states are cheap. Package presence/changes are injected through two
patches that replace only the filesystem-facing lookups of the queue.
"""
from contextlib import closing, contextmanager
import json
import random
import shutil
import sqlite3
import uuid

from InvestmentManager import foreign_offers_store as store
from InvestmentManager.integrator import sync_tasks as queue
from InvestmentManager.integrator import foreign_consistency as consistency
from InvestmentManager.integrator.portal_sync_state import _ensure_sync_tables, _insert_event

DOMESTIC_PORTALS = ('no', 'domiporta', 'tabelaofert')
ATTEMPT_STATES = ('prepared', 'transport_unknown', 'transport_confirmed', 'ack_failed', 'ack_rejected',
                  'transport_failed', 'ack_completed')
PROFILE = {'domiporta': 'domiporta', 'tabelaofert': 'tabelaofert_primary'}


_ids = random.Random()


def uid():
    return '%032x' % _ids.getrandbits(128)


class Dataset:
    """Handle returned by build(); `changed` and `baselines` drive the filesystem patches."""

    def __init__(self, root):
        self.root = root
        self.changed = set()
        self.available = set()
        self.domestic_offers = []
        self.foreign_offers = []
        self.projects = []


def init_root(root):
    (root / 'databases').mkdir(parents=True, exist_ok=True)
    (root / 'exports/domestic').mkdir(parents=True, exist_ok=True)
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn, conn:
        conn.execute('CREATE TABLE EstateData (ID TEXT, Status_oferty TEXT, Tytul TEXT, Typ_nieruchomosci TEXT)')
        _ensure_sync_tables(conn)
    store.initialize_foreign_offers_db()


def _payload(attempt, state):
    data = dict(attempt)
    data['state'] = state
    return data


def _domestic_attempt(conn, offer, portal, action, states, *, package_id=None, attempt_id=None):
    attempt_id, package_id = attempt_id or uid(), package_id or uid()
    binding = {'package_id': package_id, 'offer_id': offer, 'portal': portal, 'action': action,
               'input_fingerprint': 'f' * 64, 'zip_sha256': 'e' * 64, 'zip_size': 10, 'zip_name': 'x.zip',
               'manifest_sha256': 'd' * 64}
    payload = {'attempt_id': attempt_id, 'binding': binding, 'revision': 0, 'baseline': None,
               'prepared_seq': 0, 'state': 'prepared'}
    _insert_event(conn, offer_id=offer, portal_key=portal, event_type='export_attempt_v1', payload=payload)
    number = conn.execute('SELECT last_insert_rowid()').fetchone()[0]
    payload['prepared_seq'] = number
    conn.execute('UPDATE offer_portal_sync_events SET payload_json=? WHERE id=?',
                 (json.dumps(payload, ensure_ascii=False), number))
    for state in states[1:]:
        _insert_event(conn, offer_id=offer, portal_key=portal, event_type='export_attempt_v1',
                      payload=_payload(payload, state))
    return package_id


def _foreign_attempt(conn, anchor, portal, action, states, *, members, subject, revision):
    attempt_id = uid()
    binding = {'domain': 'foreign', 'package_id': uid(), 'subject': subject, 'members': sorted(members),
               'portal': portal, 'transport_profile': PROFILE[portal], 'action': action, 'offer_id': anchor,
               'input_fingerprint': 'f' * 64, 'input_revision': revision, 'zip_sha256': 'e' * 64, 'zip_size': 10,
               'zip_name': 'x.zip', 'manifest_sha256': 'd' * 64}
    payload = {'attempt_id': attempt_id, 'binding': binding, 'revision': revision, 'baseline': None,
               'prepared_seq': 0, 'state': 'prepared'}
    store._insert_portal_event(conn, anchor, portal, 'export_attempt_v2', payload)
    number = conn.execute('SELECT last_insert_rowid()').fetchone()[0]
    payload['prepared_seq'] = number
    conn.execute('UPDATE foreign_offer_portal_sync_events SET payload_json=? WHERE id=?',
                 (json.dumps(payload, ensure_ascii=False), number))
    for state in states[1:]:
        store._insert_portal_event(conn, anchor, portal, 'export_attempt_v2', _payload(payload, state))


def _states(rng):
    """A short attempt lifecycle ending in a random state."""
    final = rng.choice(ATTEMPT_STATES)
    path = {'prepared': ['prepared'], 'transport_unknown': ['prepared', 'transport_unknown'],
            'transport_confirmed': ['prepared', 'transport_unknown', 'transport_confirmed'],
            'ack_failed': ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_failed'],
            'ack_rejected': ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_rejected'],
            'transport_failed': ['prepared', 'transport_unknown', 'transport_failed'],
            'ack_completed': ['prepared', 'transport_unknown', 'transport_confirmed', 'ack_completed']}
    return path[final]


def build(root, seed, *, scenario=None):
    """Create a randomized but reproducible dataset in `root` (DATA_DIR must point at it)."""
    rng = random.Random(seed)
    _ids.seed(seed * 7919 + 1)
    data = Dataset(root)
    init_root(root)
    with closing(sqlite3.connect(root / 'databases/IDB.db')) as conn, conn:
        for number in range(rng.randint(2, 5)):
            offer = 10 + number
            data.domestic_offers.append(offer)
            status = rng.choice(['aktywna', 'aktywna', 'Aktywna', 'nieaktywna', 'sprzedana', None])
            kind = rng.choice(['dzialka', 'dzialka', 'mieszkanie', 'dom'])
            conn.execute('INSERT INTO EstateData VALUES (?,?,?,?)', (str(offer), status, f'Oferta {offer}', kind))
            for portal in DOMESTIC_PORTALS + ('gruntguru',):
                if rng.random() < 0.55:
                    conn.execute('INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,last_action,'
                                 'last_error,updated_at) VALUES (?,?,?,?,?,?,?)',
                                 (offer, portal, rng.choice([0, 1, 1]), rng.choice([0, 0, 1]), 'add',
                                  rng.choice([None, None, None, 'boom']), 't'))
                for _ in range(rng.choice([0, 0, 1, 1, 2])):
                    published_package = _domestic_attempt(conn, offer, portal, rng.choice(['add', 'add', 'delete']),
                                                          _states(rng))
                    if rng.random() < 0.7:
                        data.available.add(published_package)
                if rng.random() < 0.07:
                    _insert_event(conn, offer_id=offer, portal_key=portal, event_type='legacy_attempt_started', payload={})
            if rng.random() < 0.3:
                data.changed.add(offer)
        if rng.random() < 0.3:    # source row missing for a still-published pair
            conn.execute("INSERT INTO offer_portal_sync(offer_id,portal_key,is_published,needs_update,updated_at) "
                         "VALUES (99,'no',1,0,'t')")
    with closing(store.open_foreign_offers_connection()) as conn:
        conn.execute('BEGIN IMMEDIATE')
        for development in (7, 8):
            conn.execute('INSERT OR IGNORE INTO foreign_developments(id,name) VALUES (?,?)', (development, f'Project {development}'))
        data.projects = [7, 8]
        for number in range(rng.randint(3, 8)):
            offer = 20 + number
            platform = rng.choice(['cyprus_constructions', 'cyprus_constructions', 'tripinvest'])
            development = rng.choice([7, 7, 8, None]) if platform == 'cyprus_constructions' else None
            conn.execute('INSERT INTO foreign_offers(id,source_platform,source_url,offer_title,is_active,development_id) '
                         'VALUES (?,?,?,?,?,?)',
                         (offer, platform, f'https://x.invalid/{offer}', f'F{offer}', rng.choice([1, 1, 1, 0]), development))
            data.foreign_offers.append((offer, platform, development))
            for portal in ('domiporta', 'tabelaofert'):
                if rng.random() < 0.6:
                    conn.execute('INSERT INTO foreign_offer_portal_sync(foreign_offer_id,portal_key,is_published,needs_update,'
                                 'last_error) VALUES (?,?,?,?,?)',
                                 (offer, portal, rng.choice([0, 1, 1]), rng.choice([0, 0, 1]), rng.choice([None, None, None, 'boom'])))
            if rng.random() < 0.15:
                conn.execute("INSERT INTO foreign_offer_export_warnings(foreign_offer_id,warning_code,warning_message) "
                             "VALUES (?,'source_sold_out','Sold')", (offer,))
        conn.commit()
        offers = list(data.foreign_offers)
        for offer, platform, development in offers:
            for portal in ('domiporta', 'tabelaofert'):
                for _ in range(rng.choice([0, 0, 1, 2])):
                    conn.execute('BEGIN IMMEDIATE')
                    revision = consistency.revision(conn)
                    group = (portal == 'tabelaofert' and platform == 'cyprus_constructions' and development is not None
                             and rng.random() < 0.7)
                    if group:
                        members = sorted(o for o, p, d in offers if d == development)
                        if rng.random() < 0.3 and len(members) > 1:
                            members = members[:-1]       # historical membership differs from the current one
                        subject = {'kind': 'cyprus_development', 'id': development}
                        action = 'add'
                    else:
                        members, subject, action = [offer], {'kind': 'foreign_offer', 'id': offer}, rng.choice(['add', 'add', 'delete'])
                    _foreign_attempt(conn, members[0], portal, action, _states(rng), members=members, subject=subject,
                                     revision=revision)
                    conn.commit()
                    if rng.random() < 0.4:
                        conn.execute('BEGIN IMMEDIATE')
                        conn.execute('UPDATE foreign_offers SET offer_title=offer_title||? WHERE id=?', ('x', offer))
                        conn.commit()
            if platform == 'cyprus_constructions' and rng.random() < 0.2:
                conn.execute('BEGIN IMMEDIATE')
                store._insert_portal_event(conn, offer, 'tabelaofert', 'update_required',
                                           {'reason': rng.choice(['foreign_offer_development_assignment', 'other'])})
                conn.commit()
    if scenario:
        scenario(data)
    return data


@contextmanager
def patched(monkeypatch, data):
    """Replace only the filesystem-facing baseline lookups with dataset flags."""
    def metadata(base, package_id, *args, **kwargs):
        if package_id in data.available:
            return None, {'package_id': package_id}, None
        return None, None, None
    # Offer ids are encoded through the attempt lookup below.
    monkeypatch.setattr(queue.catalog, '_metadata', metadata)
    owner = {}

    def changed(root, item):
        return item.get('offer') in data.changed
    monkeypatch.setattr(queue, '_source_changed', changed)
    # item['offer'] is needed by `changed`; derive it from the history once per call.
    original = queue.catalog._metadata

    def with_offer(base, package_id, *args, **kwargs):
        diag, item, extra = original(base, package_id, *args, **kwargs)
        if item is not None:
            item = dict(item, offer=owner.get(package_id))
        return diag, item, extra
    monkeypatch.setattr(queue.catalog, '_metadata', with_offer)
    with closing(sqlite3.connect(data.root / 'databases/IDB.db')) as conn:
        for raw in conn.execute("SELECT offer_id,payload_json FROM offer_portal_sync_events WHERE event_type='export_attempt_v1'"):
            payload = json.loads(raw[1])
            owner[payload['binding']['package_id']] = raw[0]
    yield data


def clone_without_prepared(data, target):
    """Copy of D with every prepared attempt (all its events) removed: the business-need oracle input."""
    shutil.copytree(data.root, target)
    removed = 0
    for db, table, column in (('IDB.db', 'offer_portal_sync_events', 'export_attempt_v1'),
                              ('foreign_offers.db', 'foreign_offer_portal_sync_events', 'export_attempt_v2')):
        path = target / 'databases' / db
        with closing(sqlite3.connect(path)) as conn:
            conn.execute('PRAGMA recursive_triggers=OFF')
            latest = {}
            for number, raw in conn.execute(f"SELECT id,payload_json FROM {table} WHERE event_type=? ORDER BY id", (column,)):
                payload = json.loads(raw)
                latest[payload['attempt_id']] = payload['state']
            doomed = {a for a, s in latest.items() if s == 'prepared'}
            for number, raw in list(conn.execute(f"SELECT id,payload_json FROM {table} WHERE event_type=?", (column,))):
                if json.loads(raw)['attempt_id'] in doomed:
                    conn.execute(f'DELETE FROM {table} WHERE id=?', (number,))
                    removed += 1
            conn.commit()
    return removed
