# -*- coding: utf-8 -*-
"""Shared help texts and a small help button used across the tools."""

from qgis.PyQt.QtWidgets import QPushButton, QDialog, QVBoxLayout, QTextBrowser, QDialogButtonBox


HELP = {
    "loader": (
        "1 - Load GEE data & indices",
        """<h3>Load GEE data &amp; indices</h3>
<p>Builds an analysis-ready image stack from Google Earth Engine and loads
it for the rest of the workflow.</p>
<b>Steps</b>
<ol>
<li><b>Satellite &amp; dates:</b> choose a sensor (Sentinel-2, Landsat 8/9,
Sentinel-1 SAR, or the multi-sensor fusion), a date range, and a cloud
threshold. A median composite is built over that period.</li>
<li><b>AOI:</b> pick the area. <i>Administrative unit</i> uses the bundled
Cambodia boundaries (offline, fast). <i>Canvas extent</i> and
<i>Draw polygon</i> let you define any area; the tool detects which
province/district it falls in so the map layout can reuse it.</li>
<li><b>Original bands:</b> tick only the bands you need. RGB + NIR is a
good default for a fast preview; add SWIR and red-edge for classification.</li>
<li><b>Spectral indices:</b> NDVI and NDWI are pre-selected. Add others as
needed - each is computed on GEE and added as a band.</li>
<li><b>Build stack:</b> the primary button. It loads preview tiles
immediately and downloads a local multiband GeoTIFF in the background so
QGIS stays responsive.</li>
</ol>
<p><b>Tip:</b> the local GeoTIFF carries real band names (NDVI, SAVI, ...),
so the Symbology dropdowns show names, not "Band 20".</p>"""),

    "sampling": (
        "2 - Create sample points",
        """<h3>Create sample points</h3>
<p>Generates the training/validation points for classification and
accuracy assessment.</p>
<b>Key choices</b>
<ul>
<li><b>Sample size (Cochran):</b> n = z&sup2;p(1-p)/e&sup2;. Defaults
(p=0.85, e=0.05) give a statistically sound sample; lower e for more
points.</li>
<li><b>Method:</b> <i>Stratified by ESA WorldCover</i> (recommended) spreads
points across existing land-cover classes so rare classes are represented.</li>
<li><b>Allocation:</b> <i>Proportional to area</i> is the Olofsson (2014)
recommendation for validation; <i>Equal per class</i> is better for
training. For a clean design, make two sets - one of each.</li>
<li><b>Min per class:</b> Olofsson suggests 50-100 per class for
validation.</li>
</ul>
<p>Points get a 70/30 train/valid split and an ESA WorldCover hint field
to speed up labeling.</p>"""),

    "labeling": (
        "3 - Label sample points",
        """<h3>Label sample points</h3>
<p>Assign a land-cover class to each point.</p>
<ul>
<li>The canvas is prepared with ESA WorldCover shown and the heavy
imagery layers hidden. Click a class button (or the Level-2 dropdown for
detailed LU2003 classes).</li>
<li><b>4-view window:</b> shows the same point in four synchronized
panels (NDVI, NDWI, true colour, Google Satellite) so you can judge a
point from several angles at once - the best way to avoid mislabels.</li>
<li><b>GCP shapefile:</b> load field-surveyed control points; the nearest
GCP shows as a hint, and you can bulk-transfer GCP classes to nearby
points.</li>
</ul>
<p><b>Tip:</b> a point that looks like cropland on satellite but reads as
water on NDWI deserves a second look.</p>"""),

    "classify": (
        "4 - Classify & accuracy",
        """<h3>Classify &amp; accuracy</h3>
<b>Supervised</b> (uses your labeled points): Random Forest, Gradient Tree
Boost, CART, or SVM. "Compare all" ranks them. The report gives the
confusion matrix, overall accuracy, kappa, per-class producer/user
accuracy, and the area-adjusted accuracy with 95% CIs (Olofsson 2014).
<br><br>
<b>Unsupervised</b> (no labels): K-Means and other clustering algorithms
group pixels by spectral similarity. Then <b>Reclassify clusters</b> maps
each cluster to a land-cover class - several clusters can map to one class.
<br><br>
<b>Post-processing:</b> majority filter, minimum mapping unit, hole
filling, and boundary smoothing. Accuracy is assessed on the final
(post-processed) map. Use <b>Flag misclassified points</b> to find likely
labeling errors, fix them in Tool 3, and re-run.
<br><br>
<b>Improving accuracy:</b> check the J-M separability (Tool 5) first -
classes below 1.0 will always confuse. Add discriminating bands (temporal
NDVI, SAR) rather than just more points."""),

    "signatures": (
        "5 - Signatures & separability",
        """<h3>Signatures &amp; separability</h3>
<p>Diagnoses class separability <i>before</i> you classify.</p>
<ul>
<li><b>Mean signatures:</b> the average spectral profile of each class,
sampled from the stack at your labeled points.</li>
<li><b>Jeffries-Matusita matrix:</b> every class pair scored 0 (identical)
to 2 (perfectly separable). Pairs below 1.0 will confuse no matter how
many points you add - either merge them or add a band that separates
them.</li>
<li><b>Live plot:</b> interactive curves; click a legend entry to hide a
class; export to SVG/PDF for papers.</li>
</ul>"""),

    "layout": (
        "6 - Map Layout",
        """<h3>Map Layout</h3>
<p>Builds a print-ready map of the classified result.</p>
<ul>
<li><b>Area source:</b> an administrative unit, the current canvas extent,
or a drawn polygon (the AOI from Tool 1 carries through automatically).</li>
<li><b>Insets:</b> Inset 1 shows the national context (whole country, your
province highlighted); Inset 2 zooms to the district with the commune
highlighted. Each highlight has a colour and a fill style (solid or
hatched).</li>
<li><b>Institution:</b> type your institution name; it prints beside the
emblem.</li>
<li>The LULC legend is inserted after the context layers, and the accuracy line
sits at the bottom-centre of the map frame.</li>
</ul>"""),
}


def help_button(key, parent=None):
    """Return a small '?' button that opens the help text for `key`."""
    btn = QPushButton("?")
    btn.setFixedWidth(26)
    btn.setToolTip("Help for this tool")
    title, html = HELP.get(key, ("Help", "<p>No help available.</p>"))

    def _show():
        dlg = QDialog(parent)
        dlg.setWindowTitle(title)
        dlg.resize(560, 520)
        v = QVBoxLayout(dlg)
        tb = QTextBrowser()
        tb.setHtml(html)
        tb.setOpenExternalLinks(True)
        v.addWidget(tb)
        bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
        bb.rejected.connect(dlg.close)
        bb.accepted.connect(dlg.close)
        v.addWidget(bb)
        dlg.exec()

    btn.clicked.connect(_show)
    return btn
