"""INV-LC-5: Cyprus Constructions availability -> source warnings.

A confirmed Sold Out (0 available, nothing contradicting it) gives a blocking
source_sold_out warning; contradictory or incomplete data only an advisory
source_availability_unclear; confirmed availability clears both. is_active,
prices and manual CRM values never change. Throwaway SQLite.
"""
import pytest

from InvestmentManager.foreign_offers_store import set_foreign_offer_active, update_foreign_offer_fields
from InvestmentManager.foreign_sync_merge import SourceAvailability, SyncContractError
from InvestmentManager.foreign_sync_sources.cyprus import _availability, encode_unit_type_ref
from tests.investmentmanager.test_cyprus_sync_adapter import P, project, sync, unit
from tests.investmentmanager.test_foreign_developments import foreign_db, fresh_db  # noqa: F401
from tests.investmentmanager.test_foreign_sync_service import offer_row, query

REF = encode_unit_type_ref("aloha_homes", "Phase I", "type-a")
SOLD_OUT = dict(status="Sold Out", availability_text="Sold Out", available_units=0, price_text="SOLD OUT", price=None,
                installments="Sold Out")


def warnings(db, offer_id):
    return {(r["warning_code"], r["is_blocking"]) for r in
            query(db, "SELECT warning_code, is_blocking FROM foreign_offer_export_warnings WHERE foreign_offer_id = ? AND resolved_at IS NULL", offer_id)}


def source_codes(db, offer_id):
    return {code for code, _blocking in warnings(db, offer_id) if code.startswith("source_")}


def row(db):
    return offer_row(db, REF, P)


def _complete(offer_id):
    """Make the offer otherwise export-ready (Cyprus leaves these to the CRM)."""
    update_foreign_offer_fields(offer_id, {"market_type_normalized": "primary", "source_country_name": "Cypr",
                                           "category_id_domiporta": "191", "rooms_count": 3})


# Classification -----------------------------------------------------------------


@pytest.mark.parametrize("overrides, state", [
    ({}, "available"),                                                       # 4 units, status Available
    (SOLD_OUT, "sold_out"),
    (dict(SOLD_OUT, status=None, installments=None), "sold_out"),            # count 0, nothing contradicts
    (dict(available_units=0, availability_text="0", status="Available"), "unclear"),
    (dict(available_units=0, availability_text="0", status=None, installments="10% deposit"), "unclear"),
    (dict(available_units=3, price_text="SOLD OUT"), "unclear"),
    (dict(available_units=None, availability_text=None, status="Sold Out", installments=None), "unclear"),
    (dict(available_units=None, availability_text=None, status=None, installments="Key Ready"), None),
])
def test_availability_classification(overrides, state):
    result = _availability(unit(**overrides))
    assert (result.state if result else None) == state


def test_source_availability_contract():
    with pytest.raises(SyncContractError):
        SourceAvailability("maybe")


# Sync -> warnings -------------------------------------------------------------------


def test_available_unit_has_no_source_warning(fresh_db):
    sync([project()])
    assert source_codes(fresh_db, row(fresh_db)["id"]) == set()


def test_confirmed_sold_out_blocks_export_without_touching_data(fresh_db):
    sync([project()])
    offer_id = row(fresh_db)["id"]
    _complete(offer_id)
    update_foreign_offer_fields(offer_id, {"price_value": 175000})  # manual CRM price
    assert row(fresh_db)["is_export_ready"] == 1

    report = sync([project([unit(**SOLD_OUT)])])

    after = row(fresh_db)
    assert ("source_sold_out", 1) in warnings(fresh_db, offer_id)
    assert after["is_export_ready"] == 0
    assert after["is_active"] == 1
    assert after["price_value"] == 175000  # price and manual edit kept
    assert report.error_count == 0


def test_sold_out_does_not_prevent_withdrawal(fresh_db):
    sync([project([unit(**SOLD_OUT)])])
    offer_id = row(fresh_db)["id"]

    assert set_foreign_offer_active(offer_id, False, user_id=1)["changed"] is True
    assert row(fresh_db)["is_active"] == 0
    assert ("source_sold_out", 1) in warnings(fresh_db, offer_id)


@pytest.mark.parametrize("overrides", [
    dict(available_units=0, availability_text="0 units", status="Available"),
    dict(available_units=None, availability_text=None, status="Sold Out", installments=None),
])
def test_contradictory_or_incomplete_data_is_only_flagged_for_review(fresh_db, overrides):
    sync([project()])
    offer_id = row(fresh_db)["id"]
    _complete(offer_id)

    sync([project([unit(**overrides)])])

    assert warnings(fresh_db, offer_id) >= {("source_availability_unclear", 0)}
    assert "source_sold_out" not in source_codes(fresh_db, offer_id)
    assert row(fresh_db)["is_export_ready"] == 1


def test_unclear_data_does_not_clear_a_confirmed_sold_out(fresh_db):
    sync([project([unit(**SOLD_OUT)])])
    offer_id = row(fresh_db)["id"]

    sync([project([unit(available_units=0, availability_text="0", status="Available")])])

    assert source_codes(fresh_db, offer_id) == {"source_sold_out", "source_availability_unclear"}


def test_missing_availability_information_changes_nothing(fresh_db):
    sync([project([unit(**SOLD_OUT)])])
    offer_id = row(fresh_db)["id"]

    sync([project([unit(available_units=None, availability_text=None, status=None, installments=None)])])

    assert source_codes(fresh_db, offer_id) == {"source_sold_out"}


def test_confirmed_availability_clears_the_warnings_and_restores_readiness(fresh_db):
    sync([project()])
    offer_id = row(fresh_db)["id"]
    _complete(offer_id)
    sync([project([unit(**SOLD_OUT)])])
    assert row(fresh_db)["is_export_ready"] == 0

    sync([project()])  # 4 units available again

    assert source_codes(fresh_db, offer_id) == set()
    assert row(fresh_db)["is_export_ready"] == 1


def test_repeated_identical_sold_out_sync_keeps_one_row(fresh_db):
    sync([project([unit(**SOLD_OUT)])])
    sync([project([unit(**SOLD_OUT)])])
    offer_id = row(fresh_db)["id"]
    rows = query(fresh_db, "SELECT COUNT(*) AS n FROM foreign_offer_export_warnings WHERE foreign_offer_id = ? AND warning_code = 'source_sold_out'", offer_id)
    assert rows[0]["n"] == 1


def test_dry_run_writes_no_warning(fresh_db):
    from InvestmentManager.foreign_sync import sync_records
    from InvestmentManager.foreign_sync_sources.cyprus import adapt_cyprus_catalog

    sync([project()])
    adapted = adapt_cyprus_catalog([project([unit(**SOLD_OUT)])])
    sync_records(P, adapted.developments, adapted.offers, dry_run=True)

    assert source_codes(fresh_db, row(fresh_db)["id"]) == set()
