"""Portal-specific business inputs, independent of publication and attempt state.

Render XML only: no ZIP generation, HTTP, database writes or artifact lookup.
New fingerprints use exactly the captured public dictionary responses. CRM
comparisons freeze the available dictionary bytes across the entire mutation.
"""
import re
import hashlib

from InvestmentManager.export_engine import generate, runtime_paths
from InvestmentManager.export_engine.local_gateway import _legacy_text_row
from . import domestic_batch_limits as limits
from . import export_performance as performance


class ProjectionUnavailable(ValueError):
    pass


def dictionary_responses(context=None):
    from . import domestic_dictionaries
    # Cache entries are immutable tuples replaced atomically. Copying avoids
    # acquiring the dictionary lock inside input_lock (opposite ACK lock order).
    cached = domestic_dictionaries._cache.copy()
    if context is None:
        return {url: item[1] for url, item in cached.items() if item[1] is not None}
    result = {}
    for item in context.get('dictionaries', []):
        if item['status'] == 'unavailable_fallback':
            continue
        body = cached.get(item['url'], (None, None))[1]
        if body is None or hashlib.sha256(body).hexdigest() != item['sha256']:
            raise ProjectionUnavailable('Captured dictionary inputs unavailable')
        result[item['url']] = body
    return result


def projection(root, offer, location, agent, media, description, portal, action,
               *, settings=None, responses=None, conservative=False):
    from InvestmentManager.export_engine.portals import workflows as w
    data, place, contact = map(_legacy_text_row, (offer, location, agent))
    count = sum(name.startswith('offers/') and '/image_' in name.lower() for name in media)
    inputs = runtime_paths.LocalInputs(root, export_settings=settings or {}, url_responses=responses or {})
    # Reenter the existing RLock, using the batch's existing fail-fast policy.
    with performance.lock_context(limits.locked(generate._generation_lock), 'generator_lock'), generate._environment(inputs):
        option = 'insert' if action == 'add' else 'delete'
        if portal == 'no':
            payload = w.build_no_payload(data, place)
            xml = w.render_xml_no(payload, contact, description, count, option)
        elif portal == 'domiporta':
            payload = w.build_domiporta_payload(data, place, contact)
            xml = w.render_xml_dp(payload, contact, description, count, option)
        elif portal == 'tabelaofert':
            payload = w.build_tabelaofert_payload(data, place, contact)
            xml = w.render_xml_tabelaofert(payload, description, count, option)
            xml = re.sub(r'(<data>)[^<]*(</data>)', r'\1EXPORT_TIME\2', xml, count=1)
        elif portal == 'gruntguru':
            payload = (w.build_gruntguru_delete_payload(data) if action == 'delete' else
                       w.build_gruntguru_payload(data, place, contact, description))
            xml = w.render_xml_gruntguru(payload, count, option)
            for tag in ('addDate', 'activateDate', 'updateDate', 'exportDate'):
                xml = re.sub(fr'(<{tag}>)[^<]*(</{tag}>)',
                             r'\1EXPORT_TIME\2', xml, count=1)
        elif portal == 'otodom':
            # Existing legacy publication flags remain supported; this does
            # not enable Otodom preparation or add it to active export sets.
            payload = w.build_otodom_payload(data, place)
            xml = w.render_xml_od(payload, contact, description, count, option)
            xml = re.sub(r'(<Date>)[^<]*(</Date>)', r'\1EXPORT_TIME\2', xml, count=1)
        else:
            raise ValueError('Unsupported domestic projection portal')
    selected = {name: digest for name, digest in media.items()
                if action == 'add' and ('/image_' in name.lower() or
                    portal in {'no', 'otodom'} and name.startswith('agents/'))}
    result = {'xml': xml, 'media': selected}
    if conservative and portal == 'domiporta' and action == 'add':
        # Retain only unresolved dictionary-dependent inputs actually used by
        # this category. Resolved/unused fields must not dirty another portal.
        from InvestmentManager.export_engine.portals.domiporta.dictionaries import _normalize_label
        from InvestmentManager.export_engine.portals.domiporta.aliases import DOMIPORTA_ALIASES
        def label(index):
            value = _normalize_label(data[index])
            return value if value not in {'', 'nd'} else None
        unresolved = {}
        aliases = {_normalize_label(k) for k in DOMIPORTA_ALIASES['category']}
        if _normalize_label(data[1]) not in aliases:
            unresolved['category'] = label(1)
        for field, index in (('BuildingType', 13 if payload['CategoryId'] == '191' else 14),
                             ('Sewerage', 25), ('PlotType', 30)):
            if not payload[field]:
                unresolved[field] = label(index)
        if payload['CategoryId'] == '196' and not payload['CommercialUsage']:
            unresolved['CommercialUsage'] = label(32)
        unresolved['utility_flags'] = [str(data[i] or '') == 'Tak' for i in (27, 28)]
        result['unresolved_dictionary_inputs'] = unresolved
    return result


def snapshot(root, offer_id, *, responses=None, include_media=True):
    """Compare a mutation without depending on any historical package format."""
    from . import domestic_packages as prep
    from . import domestic_package_catalog as catalog
    from contextlib import closing
    import sqlite3
    with closing(sqlite3.connect((root / 'databases/IDB.db').as_uri() + '?mode=ro', uri=True)) as conn:
        if not conn.execute("SELECT 1 FROM sqlite_master WHERE lower(name)='estatedata'").fetchone():
            return None
        source = conn.execute('SELECT ID_agenta,Status_oferty FROM EstateData WHERE ID=?', (offer_id,)).fetchone()
    if source is None:
        return None
    with closing(sqlite3.connect((root / 'databases/agents.db').as_uri() + '?mode=ro', uri=True)) as conn:
        if not conn.execute('SELECT 1 FROM agents_v2 WHERE id=?', (source[0],)).fetchone():
            return {'active': str(source[1]).strip().lower() == 'aktywna',
                    'portals': {p: 'agent_missing' for p in prep.PORTALS | {'otodom'}}}
    try:
        # Missing/incomplete records are represented explicitly, not as READY.
        offer, location, agent, _ = prep._records(root, offer_id, require_active_agent=False)
    except prep.PreparationError as exc:
        if exc.status == 404:
            return None
        # The offer exists but cannot currently be exported. Do not pretend
        # that its absence proves equality. Block the write for explicit repair.
        raise
    context = {'portal': 'no', 'action': 'add'}
    # Record-only writes cannot change image bytes. Retain gallery identities
    # without rereading potentially hundreds of megabytes of unchanged photos.
    bounded_reader = catalog._input_reader()
    description_bytes = {}
    def reader(root, path):
        if path.name == f'description_{offer_id}.md':
            body = bounded_reader(root, path)
            description_bytes['body'] = body
            return body
        return bounded_reader(root, path) if include_media else b''
    _, media, _ = prep._state(root, offer_id, context, file_reader=reader,
                             max_entries=catalog.MAX_INPUT_ENTRIES, require_active_agent=False)
    description = description_bytes['body']
    description = description.decode('utf8') if description is not None else None
    result = {}
    for portal in sorted(prep.PORTALS | {'otodom'}):
        if portal == 'gruntguru' and str(offer['Typ_nieruchomosci']).strip().lower() not in {'działka', 'dzialka'}:
            result[portal] = None
            continue
        result[portal] = prep._sha(prep._json(projection(
            root, offer, location, agent, media, description, portal, 'add',
            responses=responses, conservative=not responses)))
    # Activity is a business condition even where XML does not contain it.
    return {'portals': result, 'active': str(offer['Status_oferty']).strip().lower() == 'aktywna'}


def changed_portals(before, after):
    from .domestic_packages import PORTALS
    portals = PORTALS | {'otodom'}
    if before is None or after is None:
        return portals if before != after else set()
    if before['active'] != after['active']:
        return portals
    return {p for p in portals if before['portals'][p] != after['portals'][p]}
