"""Synthetic subdivision test for greenfield_addressing (run headless with PyQGIS).

    QT_QPA_PLATFORM=offscreen python3 test_greenfield.py

Layout (metres, Maple Street centreline on y = 0, two segments 0-300 and 300-400, the
second digitised east -> west to show that segment direction does not matter). Expected numbers were worked out by hand from the rules in the post.
"""
import math
import sys

from qgis.core import (QgsApplication, QgsFeature, QgsGeometry, QgsPointXY, QgsRectangle,
                       QgsVectorLayer)

app = QgsApplication([], False)
app.initQgis()

import greenfield_addressing as ga  # noqa: E402

CRS = "EPSG:32614"


def layer(kind, fields, rows):
    lyr = QgsVectorLayer(f"{kind}?crs={CRS}&{fields}", kind, "memory")
    feats = []
    for attrs, geom in rows:
        f = QgsFeature(lyr.fields())
        f.setAttributes(attrs)
        f.setGeometry(geom)
        feats.append(f)
    lyr.dataProvider().addFeatures(feats)
    return lyr


def box(x0, y0, x1, y1):
    return QgsGeometry.fromRect(QgsRectangle(x0, y0, x1, y1))


def line(*pts):
    return QgsGeometry.fromPolylineXY([QgsPointXY(*p) for p in pts])


# --- parcels -------------------------------------------------------------------------
parcels_rows = []


def lot(name, geom):
    parcels_rows.append(([name], geom))


# North side (y 10..40), the side walked first. Seed: corner lot at Cedar Lane.
lot("N1-seed-corner", box(10, 10, 24, 40))          # 14 m on Maple, 30 m on Cedar -> Maple
for i, x in enumerate(range(24, 80, 14), start=2):
    lot(f"N{i}", box(x, 10, x + 14, 40))            # N2..N5, adjacent
# lane gap 80..104 with an unnamed lane at x = 92
for i, x in enumerate(range(104, 160, 14), start=6):
    lot(f"N{i}", box(x, 10, x + 14, 40))            # N6..N9
lot("N-park", box(160, 10, 220, 60))                # 3000 m2 -> skipped
for i, x in enumerate(range(220, 304, 14), start=10):
    lot(f"N{i}", box(x, 10, x + 14, 40))            # N10..N15, last one crosses measure 300

# South side (y -10..-40), numbered by measure against the north side.
lot("S-corner-cedar", box(10, -30, 40, -10))        # 30 m on Maple, 20 m on Cedar -> Cedar
lot("S-cedar-only", box(10, -50, 40, -30))          # faces Cedar only
lot("S1-seed", box(40, -40, 56, -10))
curved = [QgsPointXY(56, -40), QgsPointXY(72, -40), QgsPointXY(72, -10)]
curved += [QgsPointXY(72 - k * 2, -10 + 0.3 * math.sin(math.pi * k / 8)) for k in range(1, 8)]
curved += [QgsPointXY(56, -10), QgsPointXY(56, -40)]
lot("S2-curved-front", QgsGeometry.fromPolygonXY([curved]))
lot("S3", box(72, -40, 88, -10))
lot("S4", box(88, -40, 104, -10))
lot("S5-wide", box(104, -40, 144, -10))
for i, x in enumerate(range(144, 304, 16), start=6):
    lot(f"S{i}", box(x, -40, x + 16, -10))          # S6..S15; x >= 176 back onto Birch Avenue

# End of the north side: a lot cut off from Maple by an unnamed lane, facing Oak Road and
# Pine Way only (rule 3: the side ends there), then a Maple/Oak corner lot the walk must not reach
lot("X-oak-pine", box(304, 10, 318, 40))
lot("N-after-oak", box(330, 10, 344, 40))

# Corner lot with nearly equal frontages (15 m on Quince St, 16 m on Rowan Rd): asked
lot("Q-near-tie", box(710, 10, 725, 26))

# Separate check: a lot wrapped by an L-shaped street (rule 5, street bends around the lot)
lot("E-wrapped", box(570, 75, 590, 90))             # 20 m top edge, 15 m east edge

parcels = layer("Polygon", "field=name:string(40)", parcels_rows)
fid = {f["name"]: f.id() for f in parcels.getFeatures()}

streets = layer("LineString",
                "field=street_name:string(60)", [
                    (["Maple Street"], line((0, 0), (300, 0))),
                    (["Maple Street"], line((400, 0), (300, 0))),           # digitised backwards
                    (["Cedar Lane"], line((0, 200), (0, -200))),
                    ([None], line((92, 0), (92, 100))),                     # unnamed lane
                    ([None], line((304, 5), (318, 5))),                     # unnamed lane
                    (["Oak Road"], line((325, 0), (325, 100))),
                    (["Pine Way"], line((300, 50), (325, 50))),
                    (["Birch Avenue"], line((170, -60), (320, -60))),
                    (["Elm Bend"], line((500, 100), (600, 100), (600, 0))),
                    (["Quince St"], line((700, 0), (800, 0))),
                    (["Rowan Rd"], line((700, 0), (700, 100))),
                    (["Split Road"], line((0, -300), (50, -300))),          # two pieces with a gap
                    (["Split Road"], line((60, -300), (100, -300))),
                ])

# --- checks --------------------------------------------------------------------------
failures = []


def check(label, got, want):
    ok = got == want
    print(f"{'PASS' if ok else 'FAIL'}  {label}: {got}" + ("" if ok else f"  (want {want})"))
    if not ok:
        failures.append(label)


# pure helpers
check("next_number(19, 38, 4/14)", ga.next_number(19, 38, 4 / 14), 31)
check("next_number(43, 74, 4/14)", ga.next_number(43, 74, 4 / 14), 65)
ring = ga.outer_ring(parcels.getFeature(fid["S2-curved-front"]).geometry())
check("curved front: ring vertices -> edges", (len(ring) - 1, len(ga.normalised_edges(ring))), (11, 4))

sub = ga.Subdivision(parcels, streets)
p = ga.Prompter()
several = "through-lot: run street kept"
check("corner lot, shorter side on Cedar: skipped on a Maple run",
      sub.front_on(fid["S-corner-cedar"], "Maple Street", p), (None, "corner lot, addressed on Cedar Lane"))
check("same corner lot on a Cedar run -> Cedar", sub.front_on(fid["S-corner-cedar"], "Cedar Lane", p)[1],
      "corner lot: shorter frontage on the run street")
check("corner lot, shorter side on Maple -> Maple", sub.front_on(fid["N1-seed-corner"], "Maple Street", p)[1],
      "corner lot: shorter frontage on the run street")
check("seed is not subject to the corner test",
      sub.front_on(fid["S-corner-cedar"], "Maple Street", p, seed=True)[1], "seed: street picked by the user")
q = fid["Q-near-tie"]
try:
    sub.front_on(q, "Quince St", p)
    asked = None
except ga.Unanswered as e:
    asked = str(e)
check("near-tie corner lot is asked", asked, f"street:{q}")
check("near-tie answered: other street -> skipped",
      sub.front_on(q, "Quince St", ga.Prompter({f"street:{q}": "Rowan Rd"}))[1],
      "corner lot, addressed on Rowan Rd (chosen)")
check("near-tie answered: run street -> kept",
      sub.front_on(q, "Quince St", ga.Prompter({f"street:{q}": "Quince St"}))[1],
      "corner lot: run street chosen")
check("one other street only -> skipped", sub.front_on(fid["S-cedar-only"], "Maple Street", p)[1],
      "no frontage on Maple Street")
try:
    sub.front_on(fid["X-oak-pine"], "Maple Street", p)
    ended = None
except ga.EndOfSide as e:
    ended = str(e)
check("two other streets -> side ends", ended,
      f"lot {fid['X-oak-pine']} faces Oak Road and Pine Way, not Maple Street")
check("park skipped", sub.front_on(fid["N-park"], "Maple Street", p)[1], "large parcel")
check("lane edge blocked (unnamed street)",
      sorted(f.street for f in sub.frontages(fid["N5"])), ["Maple Street"])
check("through-lot keeps Maple", (sorted(f.street for f in sub.frontages(fid["S10"])),
                                  sub.front_on(fid["S10"], "Maple Street", p)[1]),
      (["Birch Avenue", "Maple Street"], several))
f, why = sub.front_on(fid["E-wrapped"], "Elm Bend", p)
check("street bends around lot -> shortest edge", (round(f.length, 1), why),
      (15.0, "street bends around the lot: shortest edge"))
check("sides", (sub.side("Maple Street", QgsPointXY(50, 10)), sub.side("Maple Street", QgsPointXY(50, -10))),
      ("L", "R"))
check("near the line -> no side", (sub.side("Maple Street", QgsPointXY(50, 0.005)),
                                   sub.side("Maple Street", QgsPointXY(50, 0.02))), (None, "L"))
check("measure on the backwards segment", round(sub.measure("Maple Street", QgsPointXY(350, 0)), 6),
      350.0)
check("side on the backwards segment", sub.side("Maple Street", QgsPointXY(350, 10)), "L")
try:
    sub.line("Split Road")
    refused = None
except ValueError as e:
    refused = str(e)
check("street with a gap refused", refused, "Split Road: segments do not join into one line (gap or branch)")

addresses = ga.address_layer(parcels.crs())
yes = {"scope": "all", "direction": "forward", "confirm": "yes"}


def numbers(street, side):
    return sorted(f["number"] for f in addresses.getFeatures()
                  if f["street"] == street and f["side"] == side)


print("\n-- run 0: seed faces Maple and Cedar, street not given")
check("street unanswered -> None",
      ga.run(parcels, streets, addresses, fid["N1-seed-corner"], 3, None, ga.Prompter(yes),
             dry_run=True), None)
pick = ga.run(parcels, streets, addresses, fid["N1-seed-corner"], 3, None,
              ga.Prompter({**yes, "street": "Maple Street"}), dry_run=True, stop_on=fid["N2"])
check("street picked for the seed", [p.number for p in pick], [3, 7])
nodir = {k: v for k, v in yes.items() if k != "direction"}
dflt = ga.run(parcels, streets, addresses, fid["N1-seed-corner"], 3, "Maple Street",
              ga.Prompter(nodir), dry_run=True, stop_on=fid["N2"])
check("direction defaults to forward", [p.number for p in dflt], [3, 7])

print("\n-- run 1: north side, walk (ends at the Oak/Pine lot)")
plan = ga.run(parcels, streets, addresses, fid["N1-seed-corner"], 3, "Maple Street", ga.Prompter(yes))
check("north side by walking", numbers("Maple Street", "L"),
      [3, 7, 11, 15, 19, 31, 35, 39, 43, 65, 69, 73, 77, 81, 85])
check("rays recorded", plan.rays.featureCount() > 0, True)

print("\n-- run 2: dry run, walk, scope = first three north lots, stop_on N2")
dry = ga.run(parcels, streets, addresses, fid["N1-seed-corner"], 3, "Maple Street",
             ga.Prompter({**yes, "scope": "selection", "replace": "yes"}),
             scope=[fid["N1-seed-corner"], fid["N2"], fid["N3"]], dry_run=True, stop_on=fid["N2"])
check("stop_on", [p.number for p in dry], [3, 7])
check("dry run wrote nothing", addresses.featureCount(), 15)

print("\n-- run 3: south side, by measure")
ga.run(parcels, streets, addresses, fid["S1-seed"], 12, "Maple Street", ga.Prompter(yes))
check("south side by measure", numbers("Maple Street", "R"),
      [12, 16, 20, 22, 32, 40, 44, 46, 48, 50, 66, 70, 74, 78, 82])

print("\n-- run 4: north again without answering 'replace' (default: no)")
before = addresses.featureCount()
check("replace defaults to no -> None", ga.run(parcels, streets, addresses, fid["N1-seed-corner"], 3,
                                   "Maple Street", ga.Prompter(yes)), None)
check("nothing written", addresses.featureCount(), before)

# The south side now exists, so re-running the north side numbers it by measure
# (post, Figure 1): the smallest valid numbers, 1, 3, 5, not a +4 walk.
print("\n-- run 5: replace the north side within a scope of three lots (by measure)")
ga.run(parcels, streets, addresses, fid["N1-seed-corner"], 1, "Maple Street",
       ga.Prompter({**yes, "scope": "selection", "replace": "yes"}),
       scope=[fid["N1-seed-corner"], fid["N2"], fid["N3"]])
check("scoped replace", numbers("Maple Street", "L"),
      [1, 3, 5, 15, 19, 31, 35, 39, 43, 65, 69, 73, 77, 81, 85])

print("\n-- GeoPackage: an existing address layer is opened, not overwritten")
import os, tempfile  # noqa: E401,E402
gpkg = os.path.join(tempfile.mkdtemp(), "addresses.gpkg")
first = ga.address_layer(parcels.crs(), gpkg)
copies = []
for f in addresses.getFeatures():           # by name: the GeoPackage adds a fid column
    g = QgsFeature(first.fields())
    g.setGeometry(f.geometry())
    for name in addresses.fields().names():
        g[name] = f[name]
    copies.append(g)
first.dataProvider().addFeatures(copies)
check("gpkg written", ga.address_layer(parcels.crs(), gpkg).featureCount(), addresses.featureCount())
other = ga.address_layer(parcels.crs(), gpkg, name="other")
check("second layer added beside it", (other.featureCount(),
      ga.address_layer(parcels.crs(), gpkg).featureCount()), (0, addresses.featureCount()))

print(f"\n{'ALL PASSED' if not failures else f'{len(failures)} FAILED: {failures}'}")
app.exitQgis()
sys.exit(1 if failures else 0)
