"""CYPRUS-PARSER-1: unit type identity is (phase_group_key, external_id).

The Cyprus Constructions project pages embed their unit types as JavaScript literals
grouped by phase:

    K={"Phase I":[{id:`type-a`,...},{id:`type-b`,...}],"Phase II":[{id:`type-a`,...}]}

`id` repeats between groups, and the old parser de-duplicated on `external_id`
alone, silently dropping every repeat (Phuket: 8 unit types in the source, 4
returned). These tests use a bundle shaped like the real Phuket one; nothing here
touches the network.
"""
import dataclasses
from dataclasses import asdict

import pytest

from integrations.cyprus_constructions import cyprus_project_details as cpd


def unit_js(unit_id, title, phase_title="Type A - Garden", *, price="£100,000", extra=""):
    return (
        f"{{id:`{unit_id}`,title:`{title}`,phaseTitle:`{phase_title}`,description:`About {title}.`,"
        f"status:`Available`,statusClass:`bg-green-500`,availability:`4 units available`,"
        f"netArea:`105 m²`,grossArea:`128 m²`,features:[`3 Bedrooms`,`2 Bathrooms`],price:`{price}`,"
        f"installments:`Key Ready / Resale`,imageSrc:`/Cover.jpg`,sitePlanImage:`/site.webp`,"
        f"floorPlanImage:`/plan.webp`,gallery:[`/g1.jpg`,`/g2.jpg`]{extra}}}"
    )


PAD = "})]}),(0,z.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),"
TAIL = ",Y=()=>{let{t:e}=n();return e(`x`)}"


def grouped(groups, variable="K"):
    body = ",".join(
        f'"{key}":[{",".join(units)}]' if not key.isidentifier() else f"{key}:[{','.join(units)}]"
        for key, units in groups
    )
    return f"{PAD}{variable}={{{body}}}{TAIL}"


def flat(units, variable="K"):
    return f"{PAD}{variable}=[{','.join(units)}]{TAIL}"


PHUKET = grouped([
    ("Phase I", [
        unit_js("type-a", "Phuket – Type A", "Type A - Garden & Penthouse"),
        unit_js("type-b", "Phuket – Type C ECO Homes", "Type B - Penthouse & Garden"),
        unit_js("type-c", "Phuket – Type C", "Type C - Exclusive Villas"),
    ]),
    ("Phase II", [
        unit_js("type-a", "Phuket – Type A 1+1", "Type A - Garden & Penthouse"),
        unit_js("type-A", "Phuket – Type A 2+1", "Type B - Penthouse & Garden"),
        unit_js("type-b", "Phuket – Type B", "Type B - Exclusive Villas"),
    ]),
    ("Phase III", [
        unit_js("type-a", "Phuket – Type A 6+1", "Type A - Luxury Villas"),
        unit_js("type-b", "Phuket – Type B 3+1", "Type B - Luxury Villas"),
    ]),
])


def parsed(bundle):
    return [cpd.parse_unit(obj, group) for group, obj in cpd.extract_unit_records(bundle)]


@pytest.fixture()
def project_from(monkeypatch):
    """extract_project() with only the network edges replaced by a fixed bundle."""
    def run(bundle, url="https://www.cyprusconstructions.com/pl/Phuket_H&W_Resort"):
        monkeypatch.setattr(cpd, "get_text", lambda session, page_url: "<html></html>")
        monkeypatch.setattr(cpd, "find_initial_script_urls", lambda html, page_url: [])
        monkeypatch.setattr(cpd, "discover_project_bundle", lambda *a, **k: ("https://cc.test/DetailPage.js", bundle))
        monkeypatch.setattr(cpd, "extract_page_sections", lambda *a, **k: ({}, {}))
        return cpd.extract_project(object(), url)

    return run


# ---------------------------------------------------------------------------
# The regression: nothing is lost
# ---------------------------------------------------------------------------


def test_phuket_shaped_bundle_yields_all_eight_unit_types():
    units = parsed(PHUKET)

    assert len(units) == 8
    assert [(u.phase_group_key, u.external_id) for u in units] == [
        ("Phase I", "type-a"), ("Phase I", "type-b"), ("Phase I", "type-c"),
        ("Phase II", "type-a"), ("Phase II", "type-A"), ("Phase II", "type-b"),
        ("Phase III", "type-a"), ("Phase III", "type-b"),
    ]  # source order


def test_extract_project_returns_all_eight_and_no_warning_about_them(project_from):
    result = project_from(PHUKET)

    assert len(result["unit_types"]) == 8
    assert not [w for w in result["warnings"] if w["code"] == "DUPLICATE_UNIT_TYPE_ID"]
    assert [u["title"] for u in result["unit_types"]][3] == "Phuket – Type A 1+1"   # the one the old parser dropped


def test_the_same_external_id_in_different_groups_survives():
    bundle = grouped([("Phase I", [unit_js("type-a", "One")]), ("Phase II", [unit_js("type-a", "Two")])])

    assert [(u.phase_group_key, u.external_id, u.title) for u in parsed(bundle)] == [
        ("Phase I", "type-a", "One"), ("Phase II", "type-a", "Two")]


def test_the_same_external_id_and_identical_text_in_different_groups_still_survives():
    same = unit_js("type-a", "Identical")
    bundle = grouped([("Phase I", [same]), ("Phase II", [same])])

    assert [u.phase_group_key for u in parsed(bundle)] == ["Phase I", "Phase II"]


def test_external_id_is_case_sensitive():
    bundle = grouped([("Phase II", [unit_js("type-a", "lower"), unit_js("type-A", "upper")])])

    assert [u.external_id for u in parsed(bundle)] == ["type-a", "type-A"]


# ---------------------------------------------------------------------------
# Duplicates inside one group
# ---------------------------------------------------------------------------


def test_a_repeat_inside_the_same_group_is_skipped_first_wins_and_reported(project_from):
    bundle = grouped([("Phase I", [unit_js("type-a", "First"), unit_js("type-a", "Second")])])

    result = project_from(bundle)

    assert [u["title"] for u in result["unit_types"]] == ["First"]
    duplicate = [w for w in result["warnings"] if w["code"] == "DUPLICATE_UNIT_TYPE_ID"]
    assert len(duplicate) == 1 and duplicate[0]["title"] == "Second" and "Phase I" in duplicate[0]["message"]


def test_byte_identical_objects_in_one_group_collapse_silently_as_before():
    same = unit_js("type-a", "Same")
    bundle = grouped([("Phase I", [same, same])])

    assert len(cpd.extract_unit_records(bundle)) == 1


def test_a_repeat_in_a_plain_array_is_deduplicated_conservatively(project_from):
    bundle = flat([unit_js("type-a", "First"), unit_js("type-a", "Second")])

    result = project_from(bundle)

    assert [(u["phase_group_key"], u["title"]) for u in result["unit_types"]] == [(None, "First")]
    assert [w["code"] for w in result["warnings"] if w["code"] == "DUPLICATE_UNIT_TYPE_ID"] == ["DUPLICATE_UNIT_TYPE_ID"]


# ---------------------------------------------------------------------------
# phase_group_key vs phaseTitle, and the rest of the data
# ---------------------------------------------------------------------------


def test_phase_group_key_is_kept_and_is_not_the_phase_title():
    units = parsed(PHUKET)
    second_phase_a = units[3]

    assert second_phase_a.phase_group_key == "Phase II"
    assert second_phase_a.phase_title == "Type A - Garden & Penthouse"   # separate display metadata, untouched
    assert all(u.phase_group_key != u.phase_title for u in units)
    # two unit types with the same phaseTitle in different groups stay distinguishable
    assert units[0].phase_title == units[3].phase_title and units[0].phase_group_key != units[3].phase_group_key


def test_the_group_key_reaches_the_project_output(project_from):
    result = project_from(PHUKET)
    assert [u["phase_group_key"] for u in result["unit_types"]] == ["Phase I"] * 3 + ["Phase II"] * 3 + ["Phase III"] * 2


def test_every_existing_unit_type_field_is_still_there_with_the_same_values(project_from):
    result = project_from(grouped([("Phase I", [unit_js("p1-type-b", "Aloha – Type A", "Phase I - Type A", price="£191,025")])]),
                          url="https://www.cyprusconstructions.com/pl/Aloha_homes")

    unit = result["unit_types"][0]
    assert {f.name for f in dataclasses.fields(cpd.UnitType)} == set(unit)   # nothing dropped, one field added
    assert unit["external_id"] == "p1-type-b" and unit["title"] == "Aloha – Type A" and unit["phase_title"] == "Phase I - Type A"
    assert unit["description"] == "About Aloha – Type A." and unit["status"] == "Available"
    assert (unit["availability_text"], unit["available_units"]) == ("4 units available", 4)
    assert (unit["net_area_text"], unit["net_area_m2"], unit["gross_area_text"], unit["gross_area_m2"]) == ("105 m²", 105, "128 m²", 128)
    assert unit["features"] == ["3 Bedrooms", "2 Bathrooms"]
    assert (unit["price_text"], unit["price"], unit["currency"]) == ("£191,025", 191025, "GBP")
    assert unit["installments"] == "Key Ready / Resale"
    assert unit["image_src"].endswith("/Cover.jpg") and unit["site_plan_image"].endswith("/site.webp")
    assert unit["floor_plan_image"].endswith("/plan.webp") and [g.rsplit("/", 1)[1] for g in unit["gallery"]] == ["g1.jpg", "g2.jpg"]
    assert unit["phase_group_key"] == "Phase I"


def test_availability_and_status_are_preserved_as_the_source_states_them():
    contradictory = unit_js("type-b", "Sold but listed", price="SOLD OUT")   # 4 units available + SOLD OUT price
    unit = parsed(grouped([("Phase I", [contradictory])]))[0]

    assert (unit.available_units, unit.status, unit.price, unit.price_text) == (4, "Available", None, "SOLD OUT")  # no reinterpretation


def test_no_rooms_floor_or_area_choice_is_derived():
    unit = parsed(grouped([("Phase I", [unit_js("type-a", "Villa 3+1 on the 2nd floor")])]))[0]
    assert not hasattr(unit, "floor") and not hasattr(unit, "bedrooms")
    assert (unit.net_area_m2, unit.gross_area_m2) == (105, 128)   # both kept, none chosen


# ---------------------------------------------------------------------------
# Projects without a group key behave as before
# ---------------------------------------------------------------------------


def test_a_plain_array_has_no_group_key_and_nothing_is_invented():
    units = parsed(flat([unit_js("type-a", "A"), unit_js("type-b", "B"), unit_js("type-c", "C")]))

    assert [u.phase_group_key for u in units] == [None, None, None]
    assert [u.external_id for u in units] == ["type-a", "type-b", "type-c"]


def test_extract_unit_objects_keeps_its_old_contract():
    objects = [unit_js("type-a", "A"), unit_js("type-b", "B")]
    assert cpd.extract_unit_objects(flat(objects)) == objects
    assert cpd.extract_unit_objects(grouped([("Phase I", objects)])) == objects


def test_a_project_with_a_single_group_is_unchanged_apart_from_the_key():
    single = parsed(grouped([("Phase I", [unit_js("type-a", "A"), unit_js("type-b", "B")])]))

    assert [(u.external_id, u.title) for u in single] == [("type-a", "A"), ("type-b", "B")]
    assert {u.phase_group_key for u in single} == {"Phase I"}


def test_group_keys_may_be_unquoted_identifiers_or_contain_odd_characters():
    bundle = grouped([("PhaseOne", [unit_js("type-a", "A")]), ("Phase II – Villas", [unit_js("type-a", "B")])])

    assert [u.phase_group_key for u in parsed(bundle)] == ["PhaseOne", "Phase II – Villas"]


def test_arrays_of_non_unit_objects_are_never_taken_for_groups():
    bundle = (
        f"{PAD}Menu={{items:[{{label:`Home`,href:`/`}}],\"Phase I\":[{unit_js('type-a', 'A')}]}}{TAIL}"
    )
    assert [u.phase_group_key for u in parsed(bundle)] == ["Phase I"]


def test_unit_type_dataclass_stays_backward_compatible_for_positional_construction():
    # the new field is last and defaulted, so existing UnitType(...) calls keep working
    fields = dataclasses.fields(cpd.UnitType)
    assert fields[-1].name == "phase_group_key" and fields[-1].default is None
    assert asdict(cpd.parse_unit(unit_js("type-a", "A")))["phase_group_key"] is None
