# -----------------------------------------------------------------------------
# Delete Grids by Name  -  Dynamo 3.x (CPython3 / PythonNet3)
#
# Deletes the grids listed in GRIDS_TO_DELETE from the active Revit project.
# Pinned grids are unpinned first. Names not found are reported, not errors.
#
# After deleting B, E and 4 from the atrium layout, the grid becomes
# symmetric: 20' / 40' / 20' in both directions.
#
#                1          2              3          5
#   A  y=80'  ---+----------+--------------+----------+---
#                |   20'    |              |          |
#   C  y=60'  ---+----------+--------------+----------+---
#                |          |    ATRIUM    |          |
#                |          |   40' x 40'  |          |
#   D  y=20'  ---+----------+--------------+----------+---
#                |          |              |          |
#   F  y= 0'  ---+----------+--------------+----------+---
#              x=0'        20'            60'        80'
#
# HOW TO USE
#   1. Open Dynamo 3.x, place a Python Script node (CPython3 or PythonNet3).
#   2. Paste this file in and Run.  Ctrl+Z in Revit undoes the whole run.
#   Optional: wire a list of names into IN[0] to delete different grids.
# -----------------------------------------------------------------------------

import clr
clr.AddReference("RevitAPI")
clr.AddReference("RevitServices")

from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

doc = DocumentManager.Instance.CurrentDBDocument

GRIDS_TO_DELETE = ["B", "E", "4"]

try:
    if IN[0]:
        names_in = IN[0] if isinstance(IN[0], (list, tuple)) else [IN[0]]
        GRIDS_TO_DELETE = [str(n) for n in names_in]
except (IndexError, NameError):
    pass

grids = {
    g.Name: g
    for g in FilteredElementCollector(doc)
    .OfCategory(BuiltInCategory.OST_Grids)
    .WhereElementIsNotElementType()
    .ToElements()
}

deleted, not_found, failed = [], [], []

TransactionManager.Instance.EnsureInTransaction(doc)
try:
    for name in GRIDS_TO_DELETE:
        grid = grids.get(name)
        if grid is None:
            not_found.append(name)
            continue
        try:
            if grid.Pinned:
                grid.Pinned = False
            doc.Delete(grid.Id)
            deleted.append(name)
        except Exception as ex:
            failed.append("{} - {}".format(name, ex))
finally:
    TransactionManager.Instance.TransactionTaskDone()

report = ["Deleted: {}".format(", ".join(deleted) or "none")]
if not_found:
    report.append("Not found: {}".format(", ".join(not_found)))
if failed:
    report.append("Could not delete:")
    report.extend(failed)

OUT = report
