"""
S3r4phNet - Geometry Validator (Oracle Spatial prep)
====================================================

Finds invalid geometries in a feature class before you load it into Oracle
Spatial (SDO_GEOMETRY), and optionally repairs them.

The default method is OGC validation. OGC is stricter than the Esri method,
and its rules on self-intersections, ring orientation and duplicate vertices
are closer to Oracle's SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT. Oracle still
applies its own tolerance, so run that check again after the load.

By default the script repairs a copy and leaves the source untouched. In-place
repair is opt-in, because Repair Geometry edits its input directly and cannot
be undone.

Runs as an ArcGIS Pro script tool or from the command line. Uses core tools
only (Check Geometry, Repair Geometry, Export Features), so no extension
checkout is needed. Requires ArcGIS Pro 3.0 or later.

Script tool parameters
----------------------
0  Input Features       Feature Layer   Required
1  Validation Method    String          Optional: OGC (default) | ESRI
2  Mode                 String          Optional: REPAIR_COPY (default) |
                                        REPORT_ONLY | REPAIR_IN_PLACE
3  Output Copy          Feature Class   Optional (REPAIR_COPY only); default <input>_repaired
4  Delete Null Shapes   Boolean         Optional, default False

Command line
------------
python GeometryValidator.py <input_fc> [OGC|ESRI]
    [REPAIR_COPY|REPORT_ONLY|REPAIR_IN_PLACE] [out_fc] [true|false]
"""
import os
import sys
from collections import Counter

import arcpy

VALIDATION_METHODS = ("OGC", "ESRI")
MODES = ("REPAIR_COPY", "REPORT_ONLY", "REPAIR_IN_PLACE")
ERROR_TABLE = r"memory\geom_errors"
MAX_LISTED = 25  # individual OIDs echoed to the log before summarising


def check(fc, method):
    """Run Check Geometry. Return a Counter of problem -> count and a sample of rows."""
    if arcpy.Exists(ERROR_TABLE):
        arcpy.management.Delete(ERROR_TABLE)
    arcpy.management.CheckGeometry(fc, ERROR_TABLE, method)

    problems, sample = Counter(), []
    with arcpy.da.SearchCursor(ERROR_TABLE, ["FEATURE_ID", "PROBLEM"]) as cursor:
        for oid, problem in cursor:
            problems[problem] += 1
            if len(sample) < MAX_LISTED:
                sample.append((oid, problem))
    arcpy.management.Delete(ERROR_TABLE)
    return problems, sample


def report(label, problems, sample):
    """Write a problem summary to the geoprocessing log."""
    total = sum(problems.values())
    if not total:
        arcpy.AddMessage(f"[PASS] {label}: no geometry problems found.")
        return
    arcpy.AddWarning(f"[WARN] {label}: {total:,} problem(s) found.")
    for problem, count in problems.most_common():
        arcpy.AddMessage(f"    {count:>7,}  {problem}")
    for oid, problem in sample:
        arcpy.AddMessage(f"    OID {oid}: {problem}")
    if total > len(sample):
        arcpy.AddMessage(f"    ... {total - len(sample):,} more not listed")


def default_copy_path(fc):
    """<input>_repaired next to the input, with a name valid for that workspace."""
    desc = arcpy.Describe(fc)
    workspace = os.path.dirname(desc.catalogPath)
    name = arcpy.ValidateTableName(f"{desc.baseName}_repaired", workspace)
    return os.path.join(workspace, name)


def validate_and_repair(fc, method="OGC", mode="REPAIR_COPY",
                        out_copy=None, delete_null=False):
    """Validate *fc* and, depending on *mode*, repair it or a copy.

    Returns the path of the feature class that is ready to load, or None when
    problems remain (or when *mode* is REPORT_ONLY and problems were found).
    """
    method, mode = method.upper(), mode.upper()
    if not arcpy.Exists(fc):
        raise ValueError(f"Input does not exist: {fc}")
    if method not in VALIDATION_METHODS:
        raise ValueError(f"Validation method must be one of {VALIDATION_METHODS}")
    if mode not in MODES:
        raise ValueError(f"Mode must be one of {MODES}")
    if arcpy.Describe(fc).dataType not in ("FeatureClass", "FeatureLayer", "ShapeFile"):
        raise ValueError(f"Input is not a feature class: {fc}")

    arcpy.env.overwriteOutput = True
    arcpy.AddMessage(f"Checking {fc} with {method} validation...")
    problems, sample = check(fc, method)
    report("Input", problems, sample)
    if not problems:
        return fc
    if mode == "REPORT_ONLY":
        return None

    if mode == "REPAIR_COPY":
        target = out_copy or default_copy_path(fc)
        arcpy.AddMessage(f"Copying to {target} before repair...")
        arcpy.conversion.ExportFeatures(fc, target)
    else:
        target = fc
        arcpy.AddWarning("REPAIR_IN_PLACE: the input itself will be modified.")

    arcpy.management.RepairGeometry(
        target,
        delete_null="DELETE_NULL" if delete_null else "KEEP_NULL",
        validation_method=method,
    )

    remaining, sample = check(target, method)
    report("After repair", remaining, sample)
    if remaining:
        arcpy.AddWarning("Some problems could not be repaired automatically; "
                         "fix them by hand before loading to Oracle.")
        return None
    arcpy.AddMessage(f"[READY] {target} passes {method} validation.")
    return target


def main():
    """Read script-tool (or command-line) parameters and run."""
    fc = arcpy.GetParameterAsText(0)
    method = arcpy.GetParameterAsText(1) or "OGC"
    mode = arcpy.GetParameterAsText(2) or "REPAIR_COPY"
    out_copy = arcpy.GetParameterAsText(3) or None
    delete_null = (arcpy.GetParameterAsText(4) or "false").lower() == "true"

    if not fc:
        arcpy.AddError(__doc__.split("Command line")[1].strip(" -\n"))
        sys.exit(1)

    try:
        ready = validate_and_repair(fc, method, mode, out_copy, delete_null)
    except arcpy.ExecuteError:
        arcpy.AddError(arcpy.GetMessages(2))
        sys.exit(1)
    except ValueError as exc:
        arcpy.AddError(str(exc))
        sys.exit(1)
    except Exception as exc:  # noqa: BLE001
        arcpy.AddError(f"Unexpected error: {exc}")
        sys.exit(1)

    if ready is None:
        arcpy.AddWarning("Data is not ready to load yet; see the problems above.")


if __name__ == "__main__":
    main()
