"""Pilot run configuration."""

# WGS84 [min_lon, min_lat, max_lon, max_lat]. Central Queenstown town basin --
# confirmed against real LINZ data: 1270 buildings, full building-outline
# coverage (capture source "Queenstown 0.1m Urban Aerial Photos (2021)"),
# DSM available (layer 105855, "Otago - Queenstown LiDAR 1m DSM (2021)").
PILOT_BBOX = [168.655, -45.045, 168.675, -45.025]
PILOT_BBOX_NZTM2000 = [1257815.95, 5002860.10, 1259272.13, 5005166.35]  # EPSG:2193, same area

# WGS84 [min_lon, min_lat, max_lon, max_lat], matching REGIONS below. This
# covers the full configured pilot/district extent plus a 30 km buffer in
# EPSG:2193: the area horizon (src/terrain_horizon.py) reaches 30 km; each
# building's far horizon (src/building_horizon.py) reaches 20 km. The metric source bounds are approximately
# [1225154.0, 4966857.5, 1305935.6, 5045588.3] in EPSG:2193.
DEM_WIDE_BBOX = [168.214585, -45.351447, 169.289392, -44.682770]

# --- Queenstown-wide expansion regions --------------------------------------
# WGS84 [min_lon, min_lat, max_lon, max_lat] per urban sub-region. Boxes are
# data-driven, not hand-drawn: candidate rectangles were validated against
# real LINZ building-outline counts (WFS), then tightened to the 2nd-98th
# percentile of actual building centroids +150m pad (with k-means splits for
# regions whose buildings cluster into separate settlements) -- fetching
# imagery for one giant rectangle spanning town-to-Arrowtown would be ~60GB
# of mostly lake and mountainside. ~9,650 buildings across these boxes
# (verified counts per box, Aug 2026) + 1,270 in the existing pilot bbox.
# The pilot itself stays on its original top-level paths; each region here
# gets its own data/regions/<name>/ tree.
# Built but NOT SERVED: regions src/combine_regions.py leaves out of the map.
# Josh, 26 Oct: "Remove mt eden from the map for now, lets get Queenstown
# working really well". Their builds stay on disk; take a name out to serve it.
SERVED_EXCLUDE = {"akl_mt_eden_ne", "akl_mt_eden_nw", "akl_mt_eden_se", "akl_mt_eden_sw",
                  "akl_epsom_01"}

REGIONS = {
    "pilot":               [168.655, -45.045, 168.675, -45.025],  # central Queenstown pilot
    # Kingston and Wanaka, added 22 Sep. Split to stay
    # inside the measured 3,000-building ceiling; each sits wholly inside its
    # LINZ LiDAR survey's actual extent, which is why the
    # bboxes are clipped rather than drawn round the townships.
    "kingston":            [168.687, -45.359, 168.749, -45.320],   # 380
    "wanaka_town":         [169.110, -44.715, 169.185, -44.670],   # 8,945
    "wanaka_albert_town":  [169.185, -44.700, 169.250, -44.660],   # 718
    "wanaka_west":         [169.092, -44.720, 169.110, -44.670],   # ~415
    "hawea":               [169.230, -44.630, 169.289, -44.606],   # ~1,826
    "town_west_fernhill":  [168.6211, -45.0463, 168.6578, -45.0295],  # 1245 buildings
    "town_gorge_north":    [168.6573, -45.0233, 168.6717, -45.0098],  # 189
    "frankton_flats":      [168.7001, -45.0309, 168.7499, -45.0147],  # 1625
    "frankton_quail_rise": [168.7337, -45.0160, 168.7600, -44.9939],  # 569
    "kelvin_heights":      [168.6791, -45.0485, 168.7196, -45.0271],  # 946
    "jacks_point":         [168.7255, -45.1017, 168.7589, -45.0724],  # 481
    "hanleys_farm":        [168.7428, -45.0742, 168.7599, -45.0609],  # 639
    "shotover_lakehayes":  [168.7335, -45.0008, 168.7814, -44.9606],  # 814
    "arthurs_point":       [168.6733, -44.9934, 168.7114, -44.9691],  # 413
    "arrowtown_millbrook": [168.7904, -44.9599, 168.8476, -44.9376],  # 2712
    # Gap-filler: the strip between shotover_lakehayes and
    # arrowtown_millbrook plus the whole Lake Hayes east side fell between
    # the original bboxes -- Speargrass Flat properties reported missing.
    "speargrass_hayes":    [168.7780, -45.0100, 168.8480, -44.9550],
    # Old Arthurs Point: lower Arthurs Point Rd / Shotover
    # bridge side fell east of the original arthurs_point bbox. 318 outlines,
    # full 2021 LiDAR coverage confirmed.
    "arthurs_point_east":  [168.7114, -45.0050, 168.7420, -44.9700],
    # Third gap region: the whole Frankton Rd arm hillside --
    # Panorama Tce, Goldfield Hts, mid-arm -- sat between the (CBD-only)
    # pilot box and frankton_flats. Never fetched, never built.
    "frankton_arm":        [168.6740, -45.0330, 168.7360, -45.0080],
    # 11 audit-derived gap regions (23 Aug): a district-wide sweep of every
    # LINZ outline vs every bbox found 1,528 uncovered buildings clustered in
    # these slivers. Bboxes computed from the uncovered clusters themselves
    # (400m clustering, 250m pad) -- no more hand-drawn coverage.
    "lake_hayes_est_west": [168.7577, -45.0144, 168.7840, -44.9983],  # 350
    "arrowtown_east":      [168.8455, -45.0066, 168.8810, -44.9612],  # 199
    "gorge_road_corridor": [168.6599, -45.0018, 168.6822, -44.9757],  # 180
    "tucker_beach":        [168.7096, -44.9725, 168.7485, -44.9478],  # 134
    # sunshine_bay_west REMOVED: 138 buildings but ZERO LiDAR tiles -- outside
    # the 2021 survey extent entirely (LINZ export: "outside-extent"). Glenorchy
    # and Kinloch were in the same category until the no-LiDAR path existed;
    # they are built on it now (see below).
    "dalefield":           [168.7491, -44.9630, 168.7924, -44.9377],  # 119
    "arrowtown_hills":     [168.8595, -44.9877, 168.8910, -44.9624],  # 79
    "frankton_arm_lake":   [168.6725, -45.0379, 168.6815, -45.0305],  # 79
    "town_south_lake":     [168.6541, -45.0275, 168.6651, -45.0209],  # 56
    "frankton_east_lake":  [168.7478, -45.0307, 168.7564, -45.0215],  # 24
    "kelvin_south":        [168.7528, -45.0519, 168.7718, -45.0405],  # 15
    # Cromwell and Bannockburn, 29 Sep: no LiDAR, so built on a synthetic
    # surface after LINZ metadata coverage checks. Boxes from the 2nd-98th
    # percentile of LINZ outline centroids +150 m, Cromwell split at its
    # median longitude to stay under the 3,000-building ceiling.
    "cromwell_west":       [169.1549, -45.0694, 169.1983, -45.0190],  # 2,699
    "cromwell_east":       [169.1931, -45.0527, 169.2196, -45.0274],  # 2,512
    "bannockburn":         [169.1326, -45.1030, 169.1814, -45.0761],  # 481
    # Glenorchy and Kinloch, head of Lake Wakatipu: no LiDAR (every published
    # Otago survey stops east of 168.57; nz-elevation STAC, 11 Oct 2026), so
    # built on a synthetic surface like Cromwell. Boxes from the 2nd-98th
    # percentile of LINZ outline centroids +150 m (13 Oct): the first,
    # street-grid boxes caught 479 and 19 of the 817 outlines at the head of
    # the lake. glenorchy now takes the town's south edge and the houses just
    # north; glenorchy_north is the Rees Valley / Paradise road group 4-6 km
    # up the valley.
    "glenorchy":           [168.3802, -44.8674, 168.4113, -44.8253],  # 528
    "kinloch":             [168.3454, -44.8471, 168.3548, -44.8272],  # 30
    "glenorchy_north":     [168.3906, -44.8087, 168.4189, -44.7775],  # 142
    # Mt Eden, Auckland (14 Oct): the suburb's 8,935 outlines (LINZ suburbs
    # layer 113764), 2nd-98th percentile of centroids +150 m, split at the
    # median into four boxes under the 3,000-building ceiling. Counts are
    # every outline in each box, neighbours' included. LINZ metadata confirms
    # Auckland LiDAR coverage at build time.
    "akl_mt_eden_nw":      [174.7398, -36.8858, 174.7512, -36.8685],  # 2,884
    "akl_mt_eden_ne":      [174.7512, -36.8856, 174.7647, -36.8683],  # 2,884
    "akl_mt_eden_sw":      [174.7401, -36.9000, 174.7512, -36.8858],  # 2,884
    "akl_mt_eden_se":      [174.7512, -36.8998, 174.7650, -36.8856],  # 2,884
}

# Default region used by tools/pipeline.py when no region argument is given.
PIPELINE_REGION = "town_gorge_north"

# Shared VM defaults for `bash quickstart.sh --mode cloud`.
# The preview cost model uses indicative rates and expected usage, then rounds
# its estimate upward; it is not a spending cap.
CLOUD_SHARED_BUILD = {
    "project": "solar-potential-map-512020",
    "vm": "claude-doing-things",
    "zone": "australia-southeast1-b",
    "ssh_user": "j",
    # Quickstart areas are LINZ locality ids, <council>/<town>/<suburb>
    # (docs/data-maintainers/choosing-an-area.md). local_region is the
    # default for local runs of tools/pipeline.py; it is kept in this block
    # because the block is left out of build keys (src/build_keys.py), so
    # changing a default rebuilds nothing. PIPELINE_REGION above is the
    # deprecated legacy default, used only when local_region is absent.
    "local_region": "queenstown-lakes-district/queenstown/sunshine-bay",
    "regions": "queenstown-lakes-district/queenstown/sunshine-bay",
    "ref": "main",
    "preview_bucket": "gs://rewiring-solar-previews",
    # Private bucket for immutable copies pushed from local staging. The
    # public preview bucket and served tiles bucket are intentionally separate.
    "artifact_staging_bucket": "gs://solar-potential-map-data",
    "preview_retention_days": 14,
    "preview_cost_model": {
        "vm_hourly_nzd": "0.24",
        "vm_hours": "8",
        "disk_monthly_per_gb_nzd": "0.24",
        "disk_gb": "100",
        "storage_gb": "1",
        "storage_monthly_per_gb_nzd": "0.03",
        "expected_download_gb": "20",
        "egress_per_gb_nzd": "0.12",
        "round_up_nzd": "0.50",
    },
}

# Buildings confirmed demolished/replaced since the 2021 capture (field
# reports) -- excluded from every build until LINZ data catches up.
# Real buildings whose top surface is not a usable roof (rooftop car decks,
# etc.) -- kept on the map, but no panels placed.
NON_ROOF_BUILDING_IDS = {
    4744271,  # 19 Industrial Pl -- rooftop parking deck
}

DEMOLISHED_BUILDING_IDS = {
    4735131,  # 61 Ballarat St -- now under the new road corridor
    # Flagged "nothing is there" while labelling roofs, 2 Sep 2026. The LiDAR is
    # from 2021 and the outlines have not caught up; each was checked against
    # current imagery and found to be bare ground or a cleared site.
    4718482, 4718539, 4744515, 5370808, 5372438, 5372729, 5372956,
}
# LINZ layers used nationally, rather than a regional survey source.
LINZ_BUILDING_OUTLINES_LAYER = 101290
# "NZ Suburbs and Localities": the official areas a region is named after
# (src/localities.py). Building outlines carry the matching suburb_locality,
# town_city and territorial_authority attributes.
LINZ_SUBURBS_LOCALITIES_LAYER = 113764
LINZ_WIDE_DEM_LAYER = 51768  # "NZ 8m Digital Elevation Model (2012)" -- distant terrain context
# What the live map shows at roof zooms: LINZ Basemaps' aerial tiles (the
# public key the page itself uses). Drawings are shifted onto this photo.
LINZ_BASEMAPS_KEY = "c01m0keqqjx0anrxjrt7grvtqxh"
LINZ_BASEMAPS_LAYER = "aerial"
# Regional DSM, DEM, LiDAR and aerial-photo layers are discovered from LINZ
# metadata and cached locally by src/surveys.py.

# Where no LiDAR exists (a survey with "elevation": "synthetic"): the one
# pitch every house roof is assumed to have, and the footprint from which a
# roof is taken to be flat and commercial. Guesses, shown on the map as such.
PHOTO_ONLY_PITCH_DEG = 20.0
PHOTO_ONLY_FLAT_MIN_M2 = 400.0


# Trina Vertex S+ TSM-500NEG18R.25 -- the panel chosen as representative
# of what is actually installed in NZ now (Lightforce, 2025). N-type i-TOPCon,
# 1961 x 1134 mm, 500 W, which works out at 22.5% module efficiency.
#
# The old 1.0 x 2.0 m / 440 W panel was a round-number stand-in. It was close
# on power density (220 vs 225 W/m2) but wrong in SHAPE, and shape is what
# decides how many fit on a narrow roof face: a real panel is half a metre
# longer and 13 cm wider than the placeholder.
PANEL_WIDTH_M = 1.134
PANEL_HEIGHT_M = 1.961
PANEL_EDGE_SETBACK_M = 0.1  # edge and ridge setbacks are 0.1 m (22 Sep); measured on the bench in the commit.
# History below is why it was 0.3 for a while. Previously: clearance from the roof's own outer edge (eave/verge) -- common
# fire-code convention. Lowered to 0.1 earlier per explicit request after it was found strangling
# narrow facets (a real ~1.4m-wide strip loses 0.6m total, under the panel's own 1m minimum
# dimension, so it fit zero panels despite real usable area, on #5371143) -- but that traded away
# realistic edge clearance on every *normal-width* facet just to rescue the rare narrow one, and
# was reported back as making edges "clearly wrong" on ordinary roofs, so it was 0.3 until
# 22 Sep, when it went back to 0.1 (the value above). The fallback below equals it, so the
# narrow-facet retry currently changes nothing.
PANEL_EDGE_SETBACK_FALLBACK_M = 0.1  # the tighter rung of the setback ladder
# (src/panel_fitting.py _ladder): every facet is packed at both setbacks, generous first, and
# the tighter fit is kept only when it holds at least SETBACK_LADDER_MIN_GAIN_PANELS (2) more
# panels, so narrow facets stay panelable without loosening the default for everything else.
# While it equals PANEL_EDGE_SETBACK_M the ladder has one rung and this changes nothing.
RIDGE_SETBACK_M = 0.1  # was 0.25 until 22 Sep. Extra clearance specifically along a boundary shared with another real
# roof plane on the same building (a real ridge, hip, or valley) -- separate from, and on top of,
# PANEL_EDGE_SETBACK_M's outer-edge clearance. Two adjacent facets each erode this far back from
# their shared boundary, so the real join between two differently-angled roof sections reads as
# an actual visible gap (like real ridge cap flashing) instead of two panel grids butting flush
# against each other with no visual break between them.
# Was 45, which was cutting off real roofs rather than unusable ones: 1/5
# Sydney St, a twelve-unit terrace whose facets are ALL 44-50 degrees, so the
# cap silently excluded the entire building and left it with 6 panels. Even a
# 90-degree panel can be economic if it faces the right way.
#
# Steepness alone does not make a panel uneconomic -- the solar
# model already prices slope and aspect, and the per-panel ROI bands already show
# a badly-oriented panel as red. A hard slope cut is doing that job twice, and
# worse.
#
# It is not raised to 90 because past this a surface is a WALL, not a roof, and
# the facets here come from points inside the building footprint, so wall
# returns collect panels.
#
# LOWERED 72 -> 55 on 1 Sep. 72 was chosen to match roof_reconstruct's
# WALL_SLOPE_DEG and to "admit every real roof including steep mansards", but it
# admitted walls too, and the cost is not spread evenly -- it is concentrated
# and total on the buildings it hits.
#
# It showed on the map at 9 Henry Street (#5371115, footprint 85 m2). Its
# four facets were 2.1, 5.6, 67.1 and 67.3 degrees, and ALL 44 PANELS -- the
# entire 19.4 kW the dashboard claimed -- sat on the two 67-degree faces. The
# actual roof got nothing. The panels also LOOK wrong there: a panel on a 67-degree wall foreshortens to 39% of its length in plan
# view, so it draws as a squat rectangle in the wrong place.
#
# District-wide this is small in aggregate and severe per building:
#     slope > 45 deg   7,685 panels  1.0%
#     slope > 55 deg   2,555 panels  0.3%
#     slope > 60 deg     506 panels  0.1%
# 55 removes 0.3% of district panels while fixing the class of building where
# the error is 100% of the claim. It stays clear of the genuinely ambiguous
# 42-50 degree band, where the markup has both real steep roofs and
# the stepped-house risers at 26 Panorama Terrace that are also walls -- that
# band needs evidence, not a threshold, and is still open.
# Best-of-N panel placement. Empty = off, which is the default.
#
# Placement is unstable with respect to its own input: a +/-10 cm nudge to a
# building outline -- far finer than the outlines are surveyed to -- moves the
# panel count by a median of 26% on a deterministic segmenter, because the
# partition is a greedy threshold search and a nudge flips the marginal cuts.
#
# Since we publish POTENTIAL, the best valid packing is the honest answer.
# Setting this to (0.05,) runs each building twice and keeps the better layout.
#
# WORTH +3.45%, measured through the real pipeline over 26 pilot buildings
# (1073 -> 1110 panels, 11 of 26 buildings moving, all upward). An earlier
# figure of +11.4% was measured on a simplified harness that skipped the panel
# gate, shading and the deep-shade veto; those absorb most of the variance,
# because they strip marginal panels whichever partition produced them.
#
# Still real capacity -- the extra panels overlap hand-marked obstructions LESS,
# and all stay inside the true outline -- but +3.45% for double the compute is a
# much weaker case than it first looked.
#
# It multiplies the most expensive stage of a district build, so turning it on
# is a compute decision, not a default.
LAYOUT_PERTURBATIONS_M = ()

MAX_ROOF_SLOPE_DEG = 55

# --- PV system assumptions ---
# These are shown to the end user in the UI, not just baked into the model
# silently -- the brief calls for transparency here. Keep this block as the
# single source of truth so the frontend can render exactly these numbers
# next to every estimate.
PV_ASSUMPTIONS = {
    "panel_rated_power_w": 500,  # W per panel at STC (Trina TSM-500NEG18R.25)
    "panel_area_m2": PANEL_WIDTH_M * PANEL_HEIGHT_M,
    "panel_efficiency_pct": 22.5,  # STC efficiency implied by 500W / 2.2238m2 / 1000W/m2
    "inverter_efficiency_pct": 97.0,  # typical string/micro-inverter conversion efficiency
    # TOTAL system losses are 16.4%, INCLUDING the inverter and glass
    # reflection (worked below). The 14% figure in the history is before
    # reflection was folded in.
    #
    # Read this with inverter_efficiency_pct above: the two multiply, and the
    # product is what matters.
    #     0.97 inverter x (1 - 0.1134) = 0.860   ->  14.0% total loss (before reflection)
    # so system_derate_pct was 11.34 rather than a round number BECAUSE losses
    # compound multiplicatively, not additively: 3% + 11% is not 14%.
    #
    # This departs from PVWatts, whose 14% default EXCLUDES the inverter (a
    # separate parameter there, default 96%) and EXCLUDES cell temperature.
    # Ours is 16.4% for everything after the panel nameplate. Shading is still
    # excluded and modelled per panel from the LiDAR, which is the one part we
    # do better than a generic loss figure.
    #
    # What the 16.4% covers: cell temperature, soiling, mismatch, wiring and
    # connections, nameplate tolerance, availability, inverter conversion, and
    # light reflected off the panel glass.
    # Light-induced degradation is ~0 because the modelled panel is n-type
    # i-TOPCon, where LID is not the p-type boron-oxygen mechanism.
    #
    # History, since this has moved three times and each move changed a public
    # number: 14% (no temperature, ~5% optimistic against PVGIS) -> 19%
    # (p-type loss budget, over-corrected) -> 15% (recalibrated for the n-type
    # panel) -> 14% total incl. inverter (+9.4% generation against the 19%
    # era, +4.2% against 15%) -> 16.4% with glass reflection, the current value.
    #
    # It sits about 5% above PVGIS (1,276 vs 1,215 kWh/kWp, measured below).
    # Deliberate: PVGIS applies a generic loss default, ours is specific to the
    # module actually modelled.
    # REFLECTION OFF THE GLASS is in it too (since 5 Nov 2026). The sky
    # model projects sunlight onto each face but nothing took off the light
    # the panel glass reflects at low angles; PVGIS puts that at 2.76% a year
    # for a north-facing 25 deg Queenstown roof (its l_aoi). Folded in here:
    #     (1 - 0.1134) x (1 - 0.0276) = 0.8621  ->  13.79%
    # so total losses are 0.97 x 0.8621 = 0.836 (16.4%). Measured against
    # PVGIS (5 Nov 2026, Queenstown, north 25 deg, its 14% system loss): the
    # map's unshaded north-facing 15-35 deg panels in pilot gave a median
    # 1,312 kWh/kWp against PVGIS's 1,215, the in-plane sunlight agreeing
    # within 1% (1,526 vs 1,510 kWh/m2); this brings it to about 1,276,
    # +5%, the rest being PVGIS's generic temperature and system losses.
    "system_derate_pct": 13.79,
    "notes": (
        "kWp = panel count x rated power at Standard Test Conditions "
        "(1000 W/m2, 25C cell temp) -- a nameplate figure, not a real-world "
        "output. Daily/annual kWh starts from pvlib clear-sky irradiance, "
        "scales it to NIWA's measured radiation record for this area, splits "
        "that into direct and diffuse light, and projects it onto each roof "
        "face's own slope and aspect using an anisotropic sky model. Each "
        "face and panel is then reduced for the terrain, trees and "
        "neighbouring buildings that actually shade it, before the inverter "
        "and system losses above -- 16.4% in total, including the inverter and light reflected off the "
        "panel glass, covering cell temperature, soiling, "
        "wiring, mismatch and downtime, which follows the industry "
        "(PVWatts) convention except that shading is not in that number: "
        "we model it per panel from the laser scan instead. Real output "
        "still varies with weather, "
        "panel brand and age, and anything that has changed since the LiDAR "
        "survey was flown -- tree growth in particular."
    ),
}
