"""
S3r4phNet - Batch Spatial Join
==============================

Spatially joins one target feature class against several join feature classes
in a single run, writing one output per join layer.

For each join layer the join runs into the ``memory`` workspace. The script
reads the match count from the in-memory result with a cursor, then exports
the result to the output workspace, so it never writes intermediates to disk.
Before joining, the script makes sure the target has a spatial index, because
an unindexed target is the usual cause of a slow Spatial Join.

Runs as an ArcGIS Pro script tool or from the command line. Uses core tools
only (Spatial Join, Add Spatial Index, Export Features), so every license
level can run it and no extension checkout is needed. Requires ArcGIS Pro 3.0
or later for Export Features.

Script tool parameters
----------------------
0  Target Features      Feature Layer        Required
1  Join Features        Feature Layer        Required, Multivalue
2  Output Workspace     Workspace            Required (file or enterprise gdb)
3  Match Option         String               Optional, default INTERSECT
4  Join Operation       String               Optional, default JOIN_ONE_TO_ONE

Command line
------------
python BatchSpatialJoin.py <target> "<join1>;<join2>" <out_gdb> [match] [operation]
"""
import os
import sys
from datetime import datetime

import arcpy

DEFAULT_MATCH_OPTION = "INTERSECT"
DEFAULT_JOIN_OPERATION = "JOIN_ONE_TO_ONE"
VALID_JOIN_OPERATIONS = ("JOIN_ONE_TO_ONE", "JOIN_ONE_TO_MANY")
MEMORY_WS = "memory"


def log(message, level="info"):
    """Timestamped message to the geoprocessing log (and stdout outside Pro)."""
    stamped = f"[{datetime.now():%H:%M:%S}] {message}"
    {"info": arcpy.AddMessage, "warn": arcpy.AddWarning,
     "error": arcpy.AddError}[level](stamped)


def split_multivalue(value):
    """Split a script-tool multivalue string into clean paths.

    Pro wraps entries that contain spaces in single quotes, e.g.
    ``'C:\\GIS Data\\a.gdb\\roads';C:\\data\\b.gdb\\rail``.
    """
    return [v.strip().strip("'\"") for v in value.split(";") if v.strip()]


def validate_inputs(target_fc, join_fcs, out_ws, join_operation):
    """Fail fast with a clear message instead of deep inside a tool."""
    problems = []
    if not arcpy.Exists(target_fc):
        problems.append(f"Target does not exist: {target_fc}")
    for fc in join_fcs:
        if not arcpy.Exists(fc):
            problems.append(f"Join layer does not exist: {fc}")
    if not arcpy.Exists(out_ws):
        problems.append(f"Output workspace does not exist: {out_ws}")
    elif arcpy.Describe(out_ws).dataType != "Workspace":
        problems.append(f"Output location is not a workspace: {out_ws}")
    if join_operation not in VALID_JOIN_OPERATIONS:
        problems.append(f"Join operation must be one of {VALID_JOIN_OPERATIONS}")
    if not join_fcs:
        problems.append("No join layers supplied.")
    for p in problems:
        log(p, "error")
    return not problems


def ensure_spatial_index(fc):
    """Add a spatial index to *fc* if it lacks one.

    Uses Describe.hasSpatialIndex. The older ListIndexes/isAscending test
    does not identify spatial indexes reliably. Failure is non-fatal: the
    join still runs, only slower (e.g. when you don't own an enterprise
    feature class).
    """
    desc = arcpy.Describe(fc)
    if getattr(desc, "hasSpatialIndex", True):
        log(f"Spatial index present on {desc.name}.")
        return
    log(f"No spatial index on {desc.name}; adding one...")
    try:
        arcpy.management.AddSpatialIndex(fc)
    except arcpy.ExecuteError:
        log("Could not add spatial index (continuing without it):\n"
            + arcpy.GetMessages(2), "warn")


def output_name(out_ws, target_fc, join_fc):
    """Build a valid, workspace-appropriate output name."""
    target = arcpy.Describe(target_fc).baseName
    join = arcpy.Describe(join_fc).baseName
    return arcpy.ValidateTableName(f"{target}_SJ_{join}", out_ws)


def matched_count(fc, join_operation):
    """Count target features that matched at least one join feature."""
    if join_operation == "JOIN_ONE_TO_MANY":
        where = "JOIN_FID <> -1"
    else:
        where = "Join_Count > 0"
    with arcpy.da.SearchCursor(fc, ["OID@"], where_clause=where) as cursor:
        return sum(1 for _ in cursor)


def join_one(target_fc, join_fc, out_ws, match_option, join_operation):
    """Join *target_fc* to *join_fc* via memory and export. Returns the output path or None."""
    name = output_name(out_ws, target_fc, join_fc)
    mem_fc = os.path.join(MEMORY_WS, name)
    out_fc = os.path.join(out_ws, name)
    try:
        arcpy.analysis.SpatialJoin(
            target_features=target_fc,
            join_features=join_fc,
            out_feature_class=mem_fc,
            join_operation=join_operation,
            join_type="KEEP_ALL",
            match_option=match_option,
        )
        total = int(arcpy.management.GetCount(mem_fc)[0])
        hits = matched_count(mem_fc, join_operation)
        arcpy.conversion.ExportFeatures(mem_fc, out_fc)
        log(f"  {name}: {hits:,} of {total:,} rows matched -> {out_fc}")
        return out_fc
    except arcpy.ExecuteError:
        log(f"Spatial Join failed for {join_fc}:\n{arcpy.GetMessages(2)}", "error")
    except Exception as exc:  # noqa: BLE001 - surface anything else, keep going
        log(f"Unexpected error joining {join_fc}: {exc}", "error")
    finally:
        if arcpy.Exists(mem_fc):
            arcpy.management.Delete(mem_fc)
    return None


def batch_spatial_join(target_fc, join_fcs, out_ws,
                       match_option=DEFAULT_MATCH_OPTION,
                       join_operation=DEFAULT_JOIN_OPERATION):
    """Run one spatial join per join layer. Returns the list of outputs written."""
    arcpy.env.overwriteOutput = True
    if not validate_inputs(target_fc, join_fcs, out_ws, join_operation):
        raise arcpy.ExecuteError("Input validation failed; see messages above.")

    log(f"Batch Spatial Join: {len(join_fcs)} join layer(s), match={match_option}, "
        f"operation={join_operation}")
    ensure_spatial_index(target_fc)

    outputs = []
    arcpy.SetProgressor("step", "Joining...", 0, len(join_fcs), 1)
    for join_fc in join_fcs:
        arcpy.SetProgressorLabel(f"Joining {os.path.basename(join_fc)}...")
        result = join_one(target_fc, join_fc, out_ws, match_option, join_operation)
        if result:
            outputs.append(result)
        arcpy.SetProgressorPosition()
    arcpy.ResetProgressor()

    failed = len(join_fcs) - len(outputs)
    log(f"Complete: {len(outputs)} succeeded, {failed} failed.",
        "warn" if failed else "info")
    return outputs


def main():
    """Read script-tool (or command-line) parameters and run."""
    target_fc = arcpy.GetParameterAsText(0)
    join_fcs = split_multivalue(arcpy.GetParameterAsText(1))
    out_ws = arcpy.GetParameterAsText(2)
    match_option = arcpy.GetParameterAsText(3) or DEFAULT_MATCH_OPTION
    join_operation = arcpy.GetParameterAsText(4) or DEFAULT_JOIN_OPERATION

    if not (target_fc and join_fcs and out_ws):
        log("Usage: BatchSpatialJoin.py <target> <join1;join2;...> <out_gdb> "
            "[match_option] [join_operation]", "error")
        sys.exit(1)

    try:
        outputs = batch_spatial_join(target_fc, join_fcs, out_ws,
                                     match_option, join_operation)
    except arcpy.ExecuteError:
        sys.exit(1)
    if not outputs:
        sys.exit(1)


if __name__ == "__main__":
    main()
