;;; ---------------------------------------------------------------------
;;;  JXNSNAP-bgol.lsp
;;;  Command:  SNJP
;;;
;;;  PURPOSE
;;;  Snaps junction-number text entities to the nearest polyline
;;;  endpoint/vertex, precisely aligning network annotation labels
;;;  (drainage, water, road-network junction numbers) with the
;;;  geometry they describe. If two or more text entities compete
;;;  for the same nearest endpoint, they are flagged instead of
;;;  auto-snapped, avoiding ambiguous overlapping annotation.
;;;
;;;  USAGE
;;;    1. Load this file (APPLOAD or drag-drop onto the drawing window).
;;;    2. Type   SNJP   at the command line and press Enter.
;;;    3. Select the junction-number text entities to snap.
;;;    4. Select the candidate polylines (network lines) to snap to.
;;;    5. Enter a search radius (or accept the default).
;;;    6. Each text is moved to the nearest polyline endpoint within
;;;       range. Any text whose nearest endpoint is contested by
;;;       another text is left untouched and recolored red for
;;;       manual review, on layer "BGOL-SNJP-FLAG".
;;;
;;;  NOTES
;;;    - This is an original, independently written implementation.
;;;      It is INSPIRED by the general idea of nearest-endpoint text
;;;      snapping utilities common in CAD/survey drafting workflows,
;;;      but the code, command name and file name here are new and
;;;      are NOT copied from, nor identical to, any specific
;;;      third-party product.
;;;
;;;  ---------------------------------------------------------------------
;;;  Developed and shared for the CAD community by:  BGol Community
;;;  Community website:                              https://bgol.in/
;;;  License:  Open-source & free to use, modify, and share for all.
;;;            Provided "as is", without warranty of any kind.
;;;  ---------------------------------------------------------------------

(vl-load-com)

(defun BGOL:SNJP-EnsureLayer (lname clr / )
  (if (not (tblsearch "LAYER" lname))
    (entmake (list '(0 . "LAYER")
                   '(100 . "AcDbSymbolTableRecord")
                   '(100 . "AcDbLayerTableRecord")
                   (cons 2 lname)
                   '(70 . 0)
                   (cons 62 clr)
                   '(6 . "Continuous")))
  )
)

;; Collect endpoints (start+end) of every polyline in a selection set.
(defun BGOL:SNJP-CollectEndpoints (plss / n i ent obj pts)
  (setq pts '())
  (setq n (sslength plss))
  (setq i 0)
  (while (< i n)
    (setq ent (ssname plss i))
    (setq obj (vlax-ename->vla-object ent))
    (setq pts (append pts (list (vlax-curve-getStartPoint obj))))
    (setq pts (append pts (list (vlax-curve-getEndPoint obj))))
    (setq i (1+ i))
  )
  pts
)

;; Find nearest point in ptlist to p, within radius; returns (point . dist) or nil.
(defun BGOL:SNJP-Nearest (p ptlist radius / best bestd d qp)
  (setq best nil bestd nil)
  (foreach qp ptlist
    (setq d (distance p qp))
    (if (and (<= d radius) (or (not bestd) (< d bestd)))
      (progn (setq best qp) (setq bestd d))
    )
  )
  (if best (cons best bestd) nil)
)

(defun C:SNJP ( / tss plss radius endpoints n i ent edata p nearest
                  assigned targets counts key flaglist movedcnt flagcnt)
  (BGOL:SNJP-EnsureLayer "BGOL-SNJP-FLAG" 1) ; red
  (setq tss (ssget '((0 . "TEXT"))))
  (if tss
    (progn
      (setq plss (ssget '((0 . "LWPOLYLINE"))))
      (if plss
        (progn
          (setq radius (getreal "\nSearch radius <5.0>: "))
          (if (not radius) (setq radius 5.0))
          (setq endpoints (BGOL:SNJP-CollectEndpoints plss))
          (setq n (sslength tss))
          ;; first pass: find each text's nearest candidate endpoint
          (setq targets '())
          (setq i 0)
          (while (< i n)
            (setq ent (ssname tss i))
            (setq edata (entget ent))
            (setq p (cdr (assoc 10 edata)))
            (setq nearest (BGOL:SNJP-Nearest p endpoints radius))
            (setq targets (append targets (list (list ent (if nearest (car nearest) nil)))))
            (setq i (1+ i))
          )
          ;; count how many texts target each endpoint
          (setq counts '())
          (foreach pr targets
            (if (cadr pr)
              (progn
                (setq key (cadr pr))
                (setq counts (append counts (list key)))
              )
            )
          )
          (setq movedcnt 0)
          (setq flagcnt 0)
          (foreach pr targets
            (setq ent (car pr))
            (setq p (cadr pr))
            (if p
              (progn
                ;; count occurrences of this exact target point
                (setq assigned 0)
                (foreach k counts (if (equal k p 1e-6) (setq assigned (1+ assigned))))
                (if (> assigned 1)
                  (progn
                    (setq edata (entget ent))
                    (setq edata (subst (cons 8 "BGOL-SNJP-FLAG") (assoc 8 edata) edata))
                    (setq edata (subst (cons 62 1) (assoc 62 edata) edata))
                    (entmod edata)
                    (entupd ent)
                    (setq flagcnt (1+ flagcnt))
                  )
                  (progn
                    (setq edata (entget ent))
                    (setq edata (subst (cons 10 p) (assoc 10 edata) edata))
                    (entmod edata)
                    (entupd ent)
                    (setq movedcnt (1+ movedcnt))
                  )
                )
              )
            )
          )
          (princ (strcat "\nSNJP: " (itoa movedcnt) " text entity(ies) snapped to junction points; "
                         (itoa flagcnt) " flagged as ambiguous on layer BGOL-SNJP-FLAG."))
        )
        (princ "\nNo candidate polylines selected.")
      )
    )
    (princ "\nNo junction text selected.")
  )
  (princ)
)

(princ "\nJXNSNAP-bgol.lsp loaded. Type SNJP to snap junction-number text to nearest polyline endpoints.")
(princ "\n  -- Free & open-source, courtesy of BGol Community (https://bgol.in/) --")
(princ)
