"""Greenfield addressing with PyQGIS.

Numbers one side of a street per run, from a seed lot and a seed number:

1. frontage: a ray from each normalised parcel edge; the edge is a front only if
   the first thing the ray hits is a named street;
2. parcel rules: large parcels; a lot facing several streets: the user picks the
   seed's street, a through-lot keeps the run's street, a corner lot goes to the
   street with the shorter frontage (skipped if that is another street), and the
   side ends at a lot not facing the run's street; several edges on one street;
3. side of the street: sign of the 2D cross product against the nearest street segment;
4. the first side is walked lot to lot (+conventional_increment when lots share an
   edge, a measured gap otherwise); the other side is numbered against it by measure;
5. whatever the rules cannot decide is asked through a Prompter. The whole plan is
   printed and confirmed before anything is written.

Street line: the segments sharing a street name are merged into one line. Its direction
is "forward", left/right are judged facing that way, and a point's measure is its
distance along it, so the street layer needs no measure attributes and segments may be
digitised either way. A street whose segments do not join into one line is refused.
Both layers must share a projected CRS in metres: all Settings lengths, areas and
tolerances are in layer units.

Only dependency: PyQGIS (qgis.core; qgis.PyQt for the optional QGIS dialog).

    import greenfield_addressing as ga
    addresses = ga.address_layer(parcels.crs(), "work/addresses.gpkg")
    ga.run(parcels, streets, addresses, seed_fid=136, seed_number=3,
           street="Maple Street", prompter=ga.QgisPrompter())
"""
from __future__ import annotations

import math
import os
from dataclasses import dataclass

from qgis.core import (QgsCoordinateTransformContext, QgsFeature, QgsGeometry, QgsPointXY,
                       QgsSpatialIndex, QgsVectorFileWriter, QgsVectorLayer)


@dataclass(frozen=True)
class Settings:
    street_field: str = "street_name"
    ray_m: float = 200.0       # frontage and search ray length
    max_lot_m2: float = 1600.0  # larger parcels are parks, reserves, future development
    merge_deg: float = 10.0    # merge consecutive pieces turning less than this ...
    short_deg: float = 45.0    # ... or less than this next to a piece shorter than short_m
    short_m: float = 2.0
    corner_deg: float = 45.0   # frontages on two streets this far apart: corner lot
    corner_tie: float = 0.10   # corner frontages within this ratio of each other: ask
    spread_deg: float = 45.0   # edges on one street this far apart: the street bends
    shared_m: float = 0.5      # common boundary that makes two lots adjacent
    on_line_m: float = 0.01    # closer than this to the street line: no side
    conventional_increment: int = 4  # number step between adjacent lots


# --- questions -------------------------------------------------------------------

class EndOfSide(Exception):
    """A lot met on the run faces several streets, none of them the run's street."""


class Unanswered(Exception):
    """A question had no valid answer; nothing is written."""


class Prompter:
    """Answers from presets ({key: answer}); subclasses add an interactive fallback."""

    def __init__(self, answers=None):
        self.answers, self.log = dict(answers or {}), []

    def ask(self, key, question, options=None, default=None):
        """options: {value: label} for a choice, None for free text.

        With no preset and no interactive answer (None), `default` is used; an empty
        answer (a cancelled dialog) or one outside `options` stops the run.
        """
        answer = self.answers.get(key)
        if answer is None:
            answer = self.interactive(question, options, default)
        if answer is None:
            answer = default
        answer = None if answer is None else str(answer).strip()
        if not answer or (options and answer not in options):
            raise Unanswered(key)
        self.log.append((key, answer))
        print(f"  ? {key}: {answer}" + (" (default)" if key not in self.answers
                                        and answer == default else ""))
        return answer

    def interactive(self, question, options, default):
        return None


class ConsolePrompter(Prompter):
    def interactive(self, question, options, default):
        if options:
            question += " [" + ", ".join(f"{v} = {label}" for v, label in options.items()) + "]"
        if default is not None:
            question += f" (Enter = {default})"
        return input(question + " ").strip() or default or ""


class QgisPrompter(Prompter):
    def interactive(self, question, options, default):
        from qgis.PyQt.QtWidgets import QInputDialog
        title = "Greenfield addressing"
        if options:
            items = [f"{v}: {label}" for v, label in options.items()]
            current = list(options).index(default) if default in options else 0
            item, ok = QInputDialog.getItem(None, title, question, items, current, False)
            return item.split(":", 1)[0] if ok else ""
        text, ok = QInputDialog.getText(None, title, question, text=str(default or ""))
        return text if ok else ""


# --- plane geometry ----------------------------------------------------------------

def _dist(p, q):
    return math.hypot(q.x() - p.x(), q.y() - p.y())


def _unit(p, q):
    d = _dist(p, q)
    return (q.x() - p.x()) / d, (q.y() - p.y()) / d


def _turn(p, q, r):
    """Degrees turned at q going p -> q -> r (0 for a straight line)."""
    ax, ay, bx, by = q.x() - p.x(), q.y() - p.y(), r.x() - q.x(), r.y() - q.y()
    return math.degrees(math.atan2(abs(ax * by - ay * bx), ax * bx + ay * by))


def _angle(u, v):
    """Undirected angle between two unit directions, 0..90 degrees."""
    return math.degrees(math.acos(min(1.0, abs(u[0] * v[0] + u[1] * v[1]))))


def outer_ring(geometry):
    """Outer ring of the (largest) polygon, true curves straightened."""
    g = QgsGeometry(geometry)
    g.convertToStraightSegment()
    if g.isMultipart():
        return max(g.asMultiPolygon(), key=lambda p: QgsGeometry.fromPolygonXY(p).area())[0]
    return g.asPolygon()[0]


def normalised_edges(ring, s=Settings()):
    """Merge consecutive ring pieces into edges; returns [(start, end), ...]."""
    if ring[0] == ring[-1]:
        ring = ring[:-1]
    n = len(ring)
    k = max(range(n), key=lambda i: _turn(ring[i - 1], ring[i], ring[(i + 1) % n]))
    ring = ring[k:] + ring[:k]           # start at the sharpest corner
    kept = [ring[0]]
    for i in range(1, n):
        prev, cur, nxt = kept[-1], ring[i], ring[(i + 1) % n]
        short = min(_dist(prev, cur), _dist(cur, nxt)) < s.short_m
        if _turn(prev, cur, nxt) >= (s.short_deg if short else s.merge_deg):
            kept.append(cur)
    return list(zip(kept, kept[1:] + kept[:1]))


def next_number(current, gap_m, coefficient):
    """current + gap x coefficient, rounded up to the same parity as current."""
    n = math.ceil(current + gap_m * coefficient - 1e-9)
    return n + 1 if (n - current) % 2 else n


# --- the subdivision ---------------------------------------------------------------

@dataclass
class Frontage:
    a: QgsPointXY
    b: QgsPointXY
    street: str
    hit: QgsPointXY            # where the frontage ray meets the street centreline

    @property
    def mid(self):
        return QgsPointXY((self.a.x() + self.b.x()) / 2, (self.a.y() + self.b.y()) / 2)

    @property
    def length(self):
        return _dist(self.a, self.b)

    @property
    def direction(self):
        return _unit(self.a, self.b)


@dataclass
class Planned:
    fid: int
    number: int
    front: Frontage
    measure: float
    reason: str


class Subdivision:
    """Parcels and street segments in memory, with spatial indexes and cached frontages."""

    def __init__(self, parcels, streets, settings=Settings()):
        self.s = settings
        self.parcels = {f.id(): f.geometry() for f in parcels.getFeatures()}
        self.parcel_index = QgsSpatialIndex(parcels.getFeatures())
        self.streets = {f.id(): (f[settings.street_field], f.geometry())
                        for f in streets.getFeatures()}
        self.street_index = QgsSpatialIndex(streets.getFeatures())
        self._lines = {}
        self.rays = []             # (geometry, kind) of every ray cast, for review
        self._fronts = {}

    # frontage detection
    def frontages(self, fid):
        if fid not in self._fronts:
            g = self.parcels[fid]
            centroid = g.centroid().asPoint()
            found = []
            for a, b in normalised_edges(outer_ring(g), self.s):
                hit = self._cast(fid, a, b, centroid)
                if hit:
                    found.append(Frontage(a, b, *hit))
            self._fronts[fid] = found
        return self._fronts[fid]

    def _cast(self, fid, a, b, centroid):
        """Ray from the edge midpoint, outward; (street, hit point) if a named street is hit first."""
        ux, uy = _unit(a, b)
        nx, ny = -uy, ux
        m = QgsPointXY((a.x() + b.x()) / 2, (a.y() + b.y()) / 2)
        if nx * (m.x() - centroid.x()) + ny * (m.y() - centroid.y()) < 0:
            nx, ny = -nx, -ny
        start = QgsPointXY(m.x() + nx * 0.01, m.y() + ny * 0.01)   # a shared edge is hit at once
        ray = QgsGeometry.fromPolylineXY(
            [start, QgsPointXY(m.x() + nx * self.s.ray_m, m.y() + ny * self.s.ray_m)])
        origin, box = QgsGeometry.fromPointXY(m), ray.boundingBox().buffered(1.0)
        lot_d = min((origin.distance(ray.intersection(self.parcels[o]))
                     for o in self.parcel_index.intersects(box)
                     if o != fid and ray.intersects(self.parcels[o])), default=math.inf)
        street = min(((origin.distance(x), name, x)
                      for sid in self.street_index.intersects(box)
                      for name, geom in [self.streets[sid]] if ray.intersects(geom)
                      for x in [ray.intersection(geom)]), key=lambda t: t[0], default=None)
        d = min(lot_d, street[0] if street else math.inf, self.s.ray_m)
        if street and street[0] < lot_d - 1e-3:
            kind = "frontage" if street[1] else "blocked_unnamed"
        else:
            kind = "blocked_parcel" if lot_d < math.inf else "no_hit"
        self.rays.append((QgsGeometry.fromPolylineXY(
            [m, QgsPointXY(m.x() + nx * d, m.y() + ny * d)]), kind))
        if kind != "frontage":
            return None
        return street[1], street[2].nearestPoint(origin).asPoint()

    # parcel rules
    def front_on(self, fid, street, prompter, seed=False):
        """(frontage addressing lot `fid` on `street`, reason), or (None, why not).

        Raises EndOfSide if the lot faces several streets and `street` is not one of them.
        The seed's street was picked by the user, so the corner test does not apply to it.
        """
        if self.parcels[fid].area() > self.s.max_lot_m2:
            return None, "large parcel"
        fronts = self.frontages(fid)
        names = {f.street for f in fronts}
        if street not in names:
            if len(names) > 1:
                raise EndOfSide(f"lot {fid} faces {' and '.join(sorted(names))}, not {street}")
            return None, f"no frontage on {street}"
        on = [f for f in fronts if f.street == street]
        why = ("single frontage" if len(names) == 1 else
               "seed: street picked by the user" if seed else "through-lot: run street kept")
        main = max(on, key=lambda f: f.length)
        for other in sorted(names - {street}) if not seed else []:
            o = max((f for f in fronts if f.street == other), key=lambda f: f.length)
            if _angle(main.direction, o.direction) < self.s.corner_deg:
                continue                                   # through-lot
            if abs(main.length / o.length - 1) <= self.s.corner_tie:
                pick = prompter.ask(f"street:{fid}", f"Corner lot {fid}: {main.length:.1f} m on "
                                    f"{street}, {o.length:.1f} m on {other}. Address it on?",
                                    {street: street, other: other})
                if pick != street:
                    return None, f"corner lot, addressed on {other} (chosen)"
                why = "corner lot: run street chosen"
            elif o.length < main.length:
                return None, f"corner lot, addressed on {other}"
            else:
                why = "corner lot: shorter frontage on the run street"
        if len(on) == 1:
            return on[0], why
        if max(_angle(p.direction, q.direction) for p in on for q in on) >= self.s.spread_deg:
            score, why = (lambda f: f.length), "street bends around the lot: shortest edge"
        else:
            score, why = (lambda f: _angle(f.direction, self.tangent(street, f.hit))), \
                "front split into pieces: edge most parallel to the street"
        best = min(score(f) for f in on)
        tied = [f for f in on if math.isclose(score(f), best, abs_tol=1e-9)]
        if len(tied) > 1:
            options = {str(i): f"{f.length:.1f} m edge at ({f.mid.x():.1f}, {f.mid.y():.1f})"
                       for i, f in enumerate(tied)}
            i = prompter.ask(f"tie:{fid}", f"Lot {fid}: edges tie on {street}. Which is the front?",
                             options)
            return tied[int(i)], "tie, chosen"
        return tied[0], why

    def shared_length(self, a, b):
        boundary = QgsGeometry(self.parcels[a].constGet().boundary())
        return boundary.intersection(self.parcels[b].buffer(0.05, 4)).length()

    # the street line: merged segments, tangent, side, measure
    def line(self, street):
        """All segments named `street` merged into one line (ValueError if they do not join)."""
        if street not in self._lines:
            parts = [g for name, g in self.streets.values() if name == street]
            merged = QgsGeometry.unaryUnion(parts).mergeLines() if parts else QgsGeometry()
            if merged.isEmpty() or merged.isMultipart():
                raise ValueError(f"{street}: segments do not join into one line (gap or branch)")
            self._lines[street] = merged
        return self._lines[street]

    def _segment(self, street, point):
        g = self.line(street)
        _, _, after, _ = g.closestSegmentWithContext(point)
        return g.vertexAt(after - 1), g.vertexAt(after)

    def tangent(self, street, point):
        return _unit(*self._segment(street, point))

    def side(self, street, point):
        a, b = self._segment(street, point)
        cross = (b.x() - a.x()) * (point.y() - a.y()) - (b.y() - a.y()) * (point.x() - a.x())
        if abs(cross) < self.s.on_line_m * _dist(a, b):     # cross / |ab| = distance to the line
            return None
        return "L" if cross > 0 else "R"

    def measure(self, street, point):
        return self.line(street).lineLocatePoint(QgsGeometry.fromPointXY(point))

    # walking
    def next_lot(self, fid, front, street, forward, eligible, prompter):
        """First eligible lot entered by a ray from the centroid along the street tangent."""
        tx, ty = self.tangent(street, front.hit)
        if not forward:
            tx, ty = -tx, -ty
        c = self.parcels[fid].centroid().asPoint()
        ray = QgsGeometry.fromPolylineXY(
            [c, QgsPointXY(c.x() + tx * self.s.ray_m, c.y() + ty * self.s.ray_m)])
        self.rays.append((ray, "search"))
        origin = QgsGeometry.fromPointXY(c)
        entered = sorted((origin.distance(ray.intersection(self.parcels[o])), o)
                         for o in self.parcel_index.intersects(ray.boundingBox().buffered(1.0))
                         if o != fid and ray.intersects(self.parcels[o]))
        for _, o in entered:
            if eligible(o):
                try:
                    f, _ = self.front_on(o, street, prompter)
                except EndOfSide as e:
                    print(f"  side ends: {e}")
                    return None
                if f:
                    return o, f
        return None


# --- one run -----------------------------------------------------------------------

class Plan(list):
    """Planned addresses in numbering order; `.rays` is a memory layer of every ray cast."""
    rays = None


def _walk(sub, street, seed, side, forward, eligible, prompter, stop_on):
    plan, c = [seed], None
    while plan[-1].fid != stop_on:
        cur = plan[-1]
        nxt = sub.next_lot(cur.fid, cur.front, street, forward, eligible, prompter)
        if nxt is None or sub.side(street, nxt[1].mid) != side or nxt[0] in {p.fid for p in plan}:
            break
        fid, front = nxt
        gap = _dist(cur.front.mid, front.mid)
        if sub.shared_length(cur.fid, fid) >= sub.s.shared_m:
            c = c or sub.s.conventional_increment / gap   # from the first adjacent pair
            n = cur.number + sub.s.conventional_increment
            why = f"shares an edge: {cur.number} + {sub.s.conventional_increment} = {n}"
        else:
            c = c or float(prompter.ask("coefficient",
                                        f"A gap comes before the coefficient is known. "
                                        f"Numbers per metre on {street}?"))
            n = next_number(cur.number, gap, c)
            why = f"no shared edge: D = {gap:.1f} m, D x c = {gap * c:.1f} -> {n}"
        plan.append(Planned(fid, n, front, sub.measure(street, front.hit), why))
    return plan


def _by_measure(sub, street, seed, side, forward, eligible, reference, prompter, stop_on):
    candidates = [seed]
    for o in sub.parcel_index.intersects(sub.line(street).boundingBox().buffered(sub.s.ray_m)):
        if o != seed.fid and eligible(o):
            try:
                f, _ = sub.front_on(o, street, prompter)
            except EndOfSide:                # not on this street: not a candidate
                continue
            if f and sub.side(street, f.mid) == side:
                candidates.append(Planned(o, 0, f, sub.measure(street, f.hit), ""))
    ahead_of = (lambda m, r: r > m) if forward else (lambda m, r: r < m)   # is r ahead of m?
    order = [p for p in sorted(candidates, key=lambda p: p.measure, reverse=not forward)
             if p is seed or ahead_of(seed.measure, p.measure)]
    plan = []
    for p in order:
        behind = [n for r, n in reference if ahead_of(r, p.measure)]
        ahead = [n for r, n in reference if ahead_of(p.measure, r)]
        if not plan:
            n, why = seed.number, "seed"
        else:
            n = plan[-1].number + 2
            while behind and n <= max(behind):
                n += 2
            why = f"measure {p.measure:.1f}: above {plan[-1].number}" + \
                  (f" and opposite {max(behind)}" if behind else "")
        if ahead and n >= min(ahead):
            print(f"  stop at lot {p.fid}: {n} is not below opposite {min(ahead)}; "
                  f"the rest stays unnumbered for review")
            break
        plan.append(Planned(p.fid, n, p.front, p.measure, why))
        if p.fid == stop_on:
            break
    return plan


def run(parcels, streets, addresses, seed_fid, seed_number=None, street=None, prompter=None, *,
        scope=None, dry_run=False, stop_on=None, settings=Settings()):
    """Address one side of `street`; returns the plan (list of Planned) or None if stopped.

    street: the run's street; if None and the seed faces several streets, it is asked.

    scope: parcel fids that may be addressed or replaced (default: the layer's selection).
    The returned plan carries `.rays`, a memory layer of every ray cast, for review.
    """
    prompter = prompter or ConsolePrompter()
    try:
        return _run(parcels, streets, addresses, seed_fid, seed_number, street, prompter,
                    scope, dry_run, stop_on, settings)
    except Unanswered as q:
        print(f"Stopped: no answer to '{q}'. Nothing written.")
        return None


def _run(parcels, streets, addresses, seed_fid, seed_number, street, prompter, scope, dry_run,
         stop_on, settings):
    selected = set(parcels.selectedFeatureIds() if scope is None else scope)
    options = {"all": "every parcel may be addressed"}
    if selected:
        options["selection"] = f"only the {len(selected)} parcels in the filter"
    in_scope = selected if prompter.ask("scope", "Which parcels may be addressed?",
                                        options) == "selection" else None

    def eligible(fid):
        return in_scope is None or fid in in_scope

    if seed_number is None:
        seed_number = int(prompter.ask("seed_number", f"Number for seed lot {seed_fid}?"))
    sub = Subdivision(parcels, streets, settings)
    names = sorted({f.street for f in sub.frontages(seed_fid)})
    if street is None and len(names) > 1:
        street = prompter.ask("street", f"Seed lot {seed_fid} faces several streets. Which one?",
                              {n: n for n in names})
    street = street or (names[0] if names else None)
    if street not in names:
        raise ValueError(f"seed lot {seed_fid} has no frontage on {street}")
    ends = sub.line(street).asPolyline()
    front, why = sub.front_on(seed_fid, street, prompter, seed=True)
    if front is None:
        raise ValueError(f"seed lot {seed_fid} cannot be addressed on {street}: {why}")
    side = sub.side(street, front.mid)
    if side is None:
        raise ValueError(f"seed lot {seed_fid}: frontage lies on the street line")
    seed = Planned(seed_fid, int(seed_number), front, sub.measure(street, front.hit), "seed")

    existing = [f for f in addresses.getFeatures() if f["street"] == street]
    replace = [f.id() for f in existing if f["side"] == side and eligible(f["parcel_fid"])]
    reference = [(f["measure"], f["number"]) for f in existing if f["side"] != side]
    if replace and prompter.ask("replace", f"{len(replace)} addresses exist on this side of "
                                f"{street}. Replace them?", {"yes": "replace", "no": "stop"},
                                default="no") != "yes":
        print("Stopped: existing addresses kept. Nothing written.")
        return None
    forward = prompter.ask("direction", "Which way do the numbers run?",
                           {"forward": f"towards the end of the street line at "
                                       f"({ends[-1].x():.0f}, {ends[-1].y():.0f})",
                            "backward": f"towards its start at ({ends[0].x():.0f}, {ends[0].y():.0f})"},
                           default="forward") == "forward"

    if reference:
        method = "by measure against the other side"
        plan = _by_measure(sub, street, seed, side, forward, eligible, reference, prompter, stop_on)
    else:
        method = "walking lot to lot"
        plan = _walk(sub, street, seed, side, forward, eligible, prompter, stop_on)
    plan = Plan(plan)
    plan.rays = _ray_layer(sub, parcels.crs())

    print(f"{street}, side {side}, {method}: {len(plan)} lots")
    for p in plan:
        print(f"  {p.number:>5}  lot {p.fid:<6} {p.reason}")
    if dry_run or not plan:
        return plan
    question = f"Write {len(plan)} addresses" + \
        (f" and delete the {len(replace)} existing on this side" if replace else "") + "?"
    if prompter.ask("confirm", question, {"yes": "write", "no": "cancel"}) != "yes":
        print("Cancelled. Nothing written.")
        return None

    features = []
    for p in plan:
        f = QgsFeature(addresses.fields())
        f.setGeometry(sub.parcels[p.fid].pointOnSurface())
        for k, v in dict(parcel_fid=p.fid, street=street, number=p.number, side=side,
                         measure=p.measure, reason=p.reason).items():
            f[k] = v
        features.append(f)
    provider = addresses.dataProvider()      # visible to layers already open in QGIS
    provider.deleteFeatures(replace)
    provider.addFeatures(features)
    addresses.updateExtents()
    addresses.triggerRepaint()
    print(f"Wrote {len(features)} addresses" + (f", replaced {len(replace)}" if replace else ""))
    return plan


# --- layers ------------------------------------------------------------------------

ADDRESS_FIELDS = ("field=parcel_fid:integer&field=street:string(120)&field=number:integer"
                  "&field=side:string(1)&field=measure:double&field=reason:string(200)")


def address_layer(crs, path=None, name="addresses"):
    """Address point layer: in memory, or layer `name` in a GeoPackage at `path`.

    An existing GeoPackage layer is opened, never overwritten; a missing one is created.
    """
    layer = QgsVectorLayer(f"Point?crs={crs.authid()}&{ADDRESS_FIELDS}", name, "memory")
    if path is None:
        return layer
    if os.path.exists(path):
        existing = QgsVectorLayer(f"{path}|layername={name}", name, "ogr")
        if existing.isValid():
            return existing
    options = QgsVectorFileWriter.SaveVectorOptions()
    options.driverName, options.layerName = "GPKG", name
    if os.path.exists(path):
        options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
    error, message, *_ = QgsVectorFileWriter.writeAsVectorFormatV3(
        layer, path, QgsCoordinateTransformContext(), options)
    if error != QgsVectorFileWriter.NoError:
        raise RuntimeError(message)
    return QgsVectorLayer(f"{path}|layername={name}", name, "ogr")


def _ray_layer(sub, crs):
    layer = QgsVectorLayer(f"LineString?crs={crs.authid()}&field=kind:string(20)", "rays", "memory")
    features = []
    for geometry, kind in sub.rays:
        f = QgsFeature(layer.fields())
        f.setGeometry(geometry)
        f["kind"] = kind
        features.append(f)
    layer.dataProvider().addFeatures(features)
    return layer
