# -*- coding: utf-8 -*-

""" #+begin_org
* ~[Summary]~ :: A =CS-Unit= for testing the DRF Executable generated by csxuFps_csu.py
#+end_org """

####+BEGIN: b:py3:cs:file/dblockControls :classification "cs-u"
""" #+begin_org
* [[elisp:(org-cycle)][| /Control Parameters Of This File/ |]] :: dblk ctrls classifications=cs-u
#+BEGIN_SRC emacs-lisp
(setq-local b:dblockControls t) ; (setq-local b:dblockControls nil)
(put 'b:dblockControls 'py3:cs:Classification "cs-u") ; one of cs-mu, cs-u, cs-lib, bpf-lib, pyLibPure
#+END_SRC
#+RESULTS:
: cs-u
#+end_org """
####+END:

####+BEGIN: b:prog:file/proclamations :outLevel 1
""" #+begin_org
* *[[elisp:(org-cycle)][| Proclamations |]]* :: Libre-Halaal Software --- Part Of BISOS ---  Poly-COMEEGA Format.
** This is Libre-Halaal Software. © Neda Communications, Inc. Subject to AGPL.
** It is part of BISOS (ByStar Internet Services OS)
** Best read and edited  with Blee in Poly-COMEEGA (Polymode Colaborative Org-Mode Enhance Emacs Generalized Authorship)
#+end_org """
####+END:

####+BEGIN: b:prog:file/particulars :authors ("./inserts/authors-mb.org")
""" #+begin_org
* *[[elisp:(org-cycle)][| Particulars |]]* :: Authors, version
** This File: /bisos/git/bxRepos/bisos-pip/csPlayer/py3/bisos/csPlayer/csmuFpsTo.py
** File True Name: /bisos/git/auth/bxRepos/bisos-pip/csPlayer/py3/bisos/csPlayer/csmuFpsTo.py
** Authors: Mohsen BANAN, http://mohsen.banan.1.byname.net/contact
#+end_org """
####+END:

####+BEGIN: b:py3:file/particulars-csInfo :status "inUse"
""" #+begin_org
* *[[elisp:(org-cycle)][| Particulars-csInfo |]]*
#+end_org """
import typing
csInfo: typing.Dict[str, typing.Any] = { 'moduleName': ['drf_csPlayer'], }
csInfo['version'] = '202602130000'
csInfo['status']  = 'inUse'
csInfo['panel'] = 'drf_csPlayer-Panel.org'
csInfo['groupingType'] = 'IcmGroupingType-pkged'
csInfo['cmndParts'] = 'IcmCmndParts[common] IcmCmndParts[param]'
####+END:

""" #+begin_org
* [[elisp:(org-cycle)][| ~Description~ |]] :: Test and inspect DRF Executable files
This is a =CS-Unit= for testing the dynamically generated drfExecutable.py files.
It validates that the generated executables can be imported and their operationsData
is correctly structured for use by drf_csPlayer_pipDevBisos3 and the DRF backend.

** Status: Testing and validation of generated DRF executables
#+end_org """

####+BEGIN: b:prog:file/orgTopControls :outLevel 1
""" #+begin_org
* [[elisp:(org-cycle)][| Controls |]] :: [[elisp:(delete-other-windows)][(1)]] | [[elisp:(show-all)][Show-All]]  [[elisp:(org-shifttab)][Overview]]  [[elisp:(progn (org-shifttab) (org-content))][Content]] | [[file:Panel.org][Panel]] | [[elisp:(blee:ppmm:org-mode-toggle)][Nat]] | [[elisp:(bx:org:run-me)][Run]] | [[elisp:(bx:org:run-me-eml)][RunEml]] | [[elisp:(progn (save-buffer) (kill-buffer))][S&Q]]  [[elisp:(save-buffer)][Save]]  [[elisp:(kill-buffer)][Quit]] [[elisp:(org-cycle)][| ]]
** /Version Control/ ::  [[elisp:(call-interactively (quote cvs-update))][cvs-update]]  [[elisp:(vc-update)][vc-update]] | [[elisp:(bx:org:agenda:this-file-otherWin)][Agenda-List]]  [[elisp:(bx:org:todo:this-file-otherWin)][ToDo-List]]

#+end_org """
####+END:

####+BEGIN: b:py3:file/workbench :outLevel 1
""" #+begin_org
* [[elisp:(org-cycle)][| Workbench |]] :: [[elisp:(python-check (format "/bisos/venv/py3/bisos3/bin/python -m pyclbr %s" (bx:buf-fname))))][pyclbr]] || [[elisp:(python-check (format "/bisos/venv/py3/bisos3/bin/python -m pydoc ./%s" (bx:buf-fname))))][pydoc]] || [[elisp:(python-check (format "/bisos/pipx/bin/pyflakes %s" (bx:buf-fname)))][pyflakes]] | [[elisp:(python-check (format "/bisos/pipx/bin/pychecker %s" (bx:buf-fname))))][pychecker (executes)]] | [[elisp:(python-check (format "/bisos/pipx/bin/pycodestyle %s" (bx:buf-fname))))][pycodestyle]] | [[elisp:(python-check (format "/bisos/pipx/bin/flake8 %s" (bx:buf-fname))))][flake8]] | [[elisp:(python-check (format "/bisos/pipx/bin/pylint %s" (bx:buf-fname))))][pylint]]  [[elisp:(org-cycle)][| ]]
#+end_org """
####+END:

####+BEGIN: b:py3:cs:orgItem/basic :type "=PyImports= "  :title "*Py Library IMPORTS*" :comment "-- Framework and External Packages Imports"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  =PyImports=  [[elisp:(outline-show-subtree+toggle)][||]] *Py Library IMPORTS* -- Framework and External Packages Imports  [[elisp:(org-cycle)][| ]]
#+end_org """
####+END:

# import os
import collections
# import pathlib
# import invoke
import ast

####+BEGIN: b:py3:cs:framework/imports :basedOn "classification"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  CsFrmWrk   [[elisp:(outline-show-subtree+toggle)][||]] *Imports* =Based on Classification=cs-u=
#+end_org """
from bisos import b
from bisos.b import cs
from bisos.b import b_io
from bisos.common import csParam

import collections
####+END:

from bisos.csPlayer import drf_csPlayer_abstract as drf

from pathlib import Path
# import importlib.util

import pathlib

import logging
logger = logging.getLogger(__name__)

####+BEGIN: b:py3:cs:orgItem/basic :type "=Executes=  "  :title "CSU-Lib Executions" :comment "-- cs.invOutcomeReportControl"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  =Executes=   [[elisp:(outline-show-subtree+toggle)][||]] CSU-Lib Executions -- cs.invOutcomeReportControl  [[elisp:(org-cycle)][| ]]
#+end_org """
####+END:

cs.invOutcomeReportControl(cmnd=True, ro=True)

####+BEGIN: b:py3:cs:orgItem/section :title "Common Parameters Specification" :comment "based on cs.param.CmndParamDict -- As expected from CSU-s"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  /Section/    [[elisp:(outline-show-subtree+toggle)][||]] *Common Parameters Specification* based on cs.param.CmndParamDict -- As expected from CSU-s  [[elisp:(org-cycle)][| ]]
#+end_org """
####+END:


####+BEGIN: b:py3:cs:func/typing :funcName "commonParamsSpecify" :comment "~CSU Specification~" :funcType "ParSpc" :deco ""
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  F-T-ParSpc [[elisp:(outline-show-subtree+toggle)][||]] /commonParamsSpecify/  ~CSU Specification~  [[elisp:(org-cycle)][| ]]
#+end_org """
def commonParamsSpecify(
####+END:
        csParams: cs.param.CmndParamDict,
) -> None:
    csParams.parDictAdd(
        parName='xuSetTree',
        parDescription="Path to a directory in which csxuFps can be found. Defaults to /bisos/var/csxu/pip_dev-bisos3",
        parDataType=None,
        parDefault=f"['pip:dev-bisos3']",
        parChoices=[],
        argparseShortOpt=None,
        argparseLongOpt='--xuSetTree',
    )



####+BEGIN: b:py3:cs:cmnd/classHead :cmndName "examples_csu" :comment "" :parsMand "" :parsOpt "" :argsMin 0 :argsMax 0 :pyInv ""
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  CmndSvc-   [[elisp:(outline-show-subtree+toggle)][||]] <<examples_csu>>  =verify= ro=cli   [[elisp:(org-cycle)][| ]]
#+end_org """
class examples_csu(cs.Cmnd):
    cmndParamsMandatory = [ ]
    cmndParamsOptional = [ ]
    cmndArgsLen = {'Min': 0, 'Max': 0,}

    @cs.track(fnLoc=True, fnEntry=True, fnExit=True)
    def cmnd(self,
             rtInv: cs.RtInvoker,
             cmndOutcome: b.op.Outcome,
    ) -> b.op.Outcome:

        failed = b_io.eh.badOutcome
        callParamsDict = {}
        if self.invocationValidate(rtInv, cmndOutcome, callParamsDict, None).isProblematic():
            return failed(cmndOutcome)
####+END:
        self.cmndDocStr(f""" #+begin_org
** [[elisp:(org-cycle)][| *CmndDesc:* | ]]  Examples of DRF Executable testing commands.
        #+end_org """)

        od = collections.OrderedDict
        cmnd = cs.examples.cmndEnter

        oneCsxuArgs = "-- 'facter.cs -i factName disks'"
        oneCsxuArgsList = "-- facter.cs -i factName disks"

        xuSetTree = "['pip:dev-bisos3']"
        xuSetTreePars = od([('xuSetTree', xuSetTree),])

        cs.examples.menuChapter('=drf_xuLineListRun=')

        cmnd('drf_xuLineListRun', pars=od(list(xuSetTreePars.items())), args=oneCsxuArgsList, comment=f"# Execute and capture results")

        cs.examples.menuChapter('=Run xuLine (One)=')

        cmnd('xuLineRun', pars=od(list(xuSetTreePars.items())), args=oneCsxuArgsList, comment=f"# Execute and capture results")

        cs.examples.menuChapter('=Run xuLines=')

        # pyCmnd_xuLineRun("From Function")

        cmnd('xuLinesRun', pars=od(list(xuSetTreePars.items())), args=oneCsxuArgs, comment=f"# Execute and capture results")
        cmnd('xuLinesRun', pars=od(list(xuSetTreePars.items())), wrapper=f"echo {oneCsxuArgs} |", comment=f"# From Stdin")

        return(cmndOutcome)

####+BEGIN: blee:bxPanel:foldingSection :outLevel 0 :sep nil :title "Functions" :anchor ""  :extraInfo ""
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*     [[elisp:(outline-show-subtree+toggle)][| _Functions_: |]]    [[elisp:(org-shifttab)][<)]] E|
#+end_org """
####+END:


####+BEGIN: b:py3:cs:func/typing :funcName "drf_xuLineRun" :funcType "extTyped" :deco "track"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  F-T-extTyped [[elisp:(outline-show-subtree+toggle)][||]] /drf_xuLineRun/  deco=track  [[elisp:(org-cycle)][| ]]
#+end_org """
@cs.track(fnLoc=True, fnEntry=True, fnExit=True)
def drf_xuLineRun(
####+END:
        xuSetTree: list[str],
        xuLineList: list[str],
        destinations: list[str],
) -> dict | None:
    """ #+begin_org
** [[elisp:(org-cycle)][| *DocStr | ]
#+end_org """

    xuName = xuLineList[0]

    xuSetTreeName = xuSetTree[0]

    xuSetBaseDir = xuSetTreeNameToXuSetBaseDir(xuSetTreeName)

    if xuSetBaseDir is None:
        print(f"EH.critical xuName '{xuName}' not found in {xuSetBaseDir}")
        return None

    xuNamePath = xuNameInXuSetBaseDir(
        xuName,
        xuSetBaseDir,
    )

    if xuNamePath is None:
        #b_io.eh.critical(f"xuName '{xuName}' not found in {xuSetBaseDir}")
        print(f"xuName '{xuName}' not found in {xuSetBaseDir}")
        return None

    # xuLineStr = ' '.join(xuLineList)

    if not (results := xuLineRun().pyCmnd(
            argsList=xuLineList,
            xuSetTree=f"{xuSetTree}",
    ).results):
        # b_io.eh.critical(f"xuName '{xuName}' execution failed with xuSetTree {xuSetTree}")
        print(f"xuName '{xuName}' execution failed with xuSetTree {xuSetTree} -- results={results}")
        return(None)

    return results


####+BEGIN: b:py3:cs:func/typing :funcName "pyCmnd_xuLineRunOBSOLETE" :funcType "extTyped" :deco "track"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  F-T-extTyped [[elisp:(outline-show-subtree+toggle)][||]] /pyCmnd_xuLineRunOBSOLETE/  deco=track  [[elisp:(org-cycle)][| ]]
#+end_org """
@cs.track(fnLoc=True, fnEntry=True, fnExit=True)
def pyCmnd_xuLineRunOBSOLETE(
####+END:
        xuLineStr: str,
        xuSetTree: list[str] = ['pip:dev-bisos3'],
) -> None:
    """ #+begin_org
** [[elisp:(org-cycle)][| *DocStr | ]
#+end_org """

    if xuLinesRun().pyCmnd(
            pyStdinArgs=[xuLineStr,],
            xuSetTree=xuSetTree,
    ).isProblematic():
                return(None)

####+BEGIN: b:py3:cs:func/typing :funcName "findOrCreateDateTagDir" :funcType "extTyped" :deco "track"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  F-T-extTyped [[elisp:(outline-show-subtree+toggle)][||]] /findOrCreateDateTagDir/  deco=track  [[elisp:(org-cycle)][| ]]
#+end_org """
@cs.track(fnLoc=True, fnEntry=True, fnExit=True)
def findOrCreateDateTagDir(
####+END:
        userAuditTrailDir: Path,
        curTime: str,
) -> Path | None:
    """ #+begin_org
** [[elisp:(org-cycle)][| *DocStr | ]
Find or create a unique timestamped directory with collision avoidance.
If the directory with curTime already exists, append -1, -2, -3, etc. until unique.
Returns the Path to the created directory, or None on failure.
#+end_org """
    
    # Start with the base directory name
    dateTag = curTime
    suffix = 0
    
    while True:
        # Construct candidate directory name
        if suffix == 0:
            candidateDir = userAuditTrailDir / dateTag
        else:
            candidateDir = userAuditTrailDir / f"{dateTag}-{suffix}"
        
        # Check if it exists
        if not candidateDir.exists():
            # Create the unique directory
            try:
                candidateDir.mkdir(parents=True, exist_ok=True)
                return candidateDir
            except Exception as e:
                b_io.eh.critical(f"Failed to create dateTag directory {candidateDir}: {e}")
                return None
        
        # Directory exists, increment suffix and try again
        suffix += 1

####+BEGIN: b:py3:cs:func/typing :funcName "pathForXuSetTree" :funcType "extTyped" :deco "track"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  F-T-extTyped [[elisp:(outline-show-subtree+toggle)][||]] /pathForXuSetTree/  deco=track  [[elisp:(org-cycle)][| ]]
#+end_org """
@cs.track(fnLoc=True, fnEntry=True, fnExit=True)
def pathForXuSetTree(
####+END:
        xuSetTree: list[str],
) -> str | None:
    """ #+begin_org
** [[elisp:(org-cycle)][| *DocStr | ]
Map xuSetTree to a Python virtual environment base path.
Takes the first element of xuSetTree and maps it to the corresponding venv path.
Returns the path to the bin directory of the virtual environment, or None on failure.
#+end_org """
    
    # Mapping dictionary for xuSetTree names to venv paths
    xuSetTreeMapping = {
        'pip:dev-bisos3': '/bisos/venv/py3/dev-bisos3/bin',
    }
    
    if not xuSetTree or len(xuSetTree) == 0:
        b_io.eh.critical("xuSetTree is empty")
        return None
    
    xuSetTreeName = xuSetTree[0]
    
    if xuSetTreeName not in xuSetTreeMapping:
        b_io.eh.critical(f"xuSetTree '{xuSetTreeName}' not found in mapping")
        return None
    
    return xuSetTreeMapping[xuSetTreeName]

####+BEGIN: b:py3:cs:func/typing :funcName "xuSetTreeNameToXuSetBaseDir" :funcType "extTyped" :deco "track"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  F-T-extTyped [[elisp:(outline-show-subtree+toggle)][||]] /xuSetTreeNameToXuSetBaseDir/  deco=track  [[elisp:(org-cycle)][| ]]
#+end_org """
@cs.track(fnLoc=True, fnEntry=True, fnExit=True)
def xuSetTreeNameToXuSetBaseDir(
####+END:
        folderName: str,
) -> pathlib.Path | None:
    nameToBaseDict = {
        "pip:bisos3": "/bisos/var/csxu/pip_bisos3/enabled",
        "pip:dev-bisos3": "/bisos/var/csxu/pip_dev-bisos3/enabled",
        "pipx": "/bisos/var/csxu/pipx/enabled",
        "modules:facter": "/bisos/var/csxu/moduled/facterModule.cs/enabled",
        "modules:soncli": "/bisos/var/csxu/moduled/soncli.cs/enabled",
    }

    if folderName not in nameToBaseDict:
        logger.error(f"Unknown folderName: {folderName}. Valid options are: {list(nameToBaseDict.keys())}")
        return None

    basePath = pathlib.Path(nameToBaseDict[folderName])

    if not basePath.exists():
        logger.error(f"Directory does not exist: {basePath}")
        return None

    if not basePath.is_dir():
        logger.error(f"Path is not a directory: {basePath}")
        return None

    return basePath


####+BEGIN: b:py3:cs:func/typing :funcName "csxuFolderObtain" :funcType "extTyped" :deco "track"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  F-T-extTyped [[elisp:(outline-show-subtree+toggle)][||]] /csxuFolderObtain/  deco=track  [[elisp:(org-cycle)][| ]]
#+end_org """
@cs.track(fnLoc=True, fnEntry=True, fnExit=True)
def csxuFolderObtain(
####+END:
      csxuFolder: drf.OperationFolder,
) -> drf.OperationFolder | None:
    """ Create list of executables """

    if csxuFolder is None:
        logger.error("csxuFolder parameter is None")
        return None

    folderName = csxuFolder.name
    if not folderName:
        logger.error("csxuFolder.name is empty")
        return None

    # Get the enabled base directory using the folder name
    enabledBaseDir = xuSetTreeNameToXuSetBaseDir(folderName)

    if enabledBaseDir is None:
        logger.error(f"Failed to get enabled base directory for folder: {folderName}")
        return None

    try:
        for each in enabledBaseDir.iterdir():
            if each.is_dir():
                csxuFolder.portfolio.append(drf.Operation(name=each.name, operation_type=drf.OperationType.PIPX))
    except OSError as e:
        logger.error(f"Error iterating directory {enabledBaseDir}: {e}")
        return None
    except Exception as e:
        logger.error(f"Unexpected error in csxuFolderObtain: {e}")
        return None

    return csxuFolder


####+BEGIN: b:py3:cs:func/typing :funcName "xuNameInXuSetBaseDir" :funcType "extTyped" :deco "track"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  F-T-extTyped [[elisp:(outline-show-subtree+toggle)][||]] /xuNameInXuSetBaseDir/  deco=track  [[elisp:(org-cycle)][| ]]
#+end_org """
@cs.track(fnLoc=True, fnEntry=True, fnExit=True)
def xuNameInXuSetBaseDir(
####+END:
        xuName: str,
        xuSetBaseDir: pathlib.Path,
) -> pathlib.Path | None:
    """ Walkthrough xuSetBaseDir to find the specified xuName """
    if xuSetBaseDir is None:
        logger.error("xuSetBaseDir parameter is None")
        return None

    xuNamePath = xuSetBaseDir / xuName

    if not xuNamePath.exists():
        logger.error(f"xuName '{xuName}' not found in {xuSetBaseDir}")
        return None

    if not xuNamePath.is_dir():
        logger.error(f"xuName path is not a directory: {xuNamePath}")
        return None

    return xuNamePath




####+BEGIN: blee:bxPanel:foldingSection :outLevel 0 :sep nil :title "Direct Command Services" :anchor ""  :extraInfo "Examples and CSs"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*     [[elisp:(outline-show-subtree+toggle)][| _Direct Command Services_: |]]  Examples and CSs  [[elisp:(org-shifttab)][<)]] E|
#+end_org """
####+END:


####+BEGIN: b:py3:cs:cmnd/classHead :cmndName "xuLineRun" :comment "" :extent "verify" :ro "cli" :parsMand "" :parsOpt "xuSetTree" :argsMin 0 :argsMax 9999 :pyInv ""
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  CmndSvc-   [[elisp:(outline-show-subtree+toggle)][||]] <<xuLineRun>>  =verify= parsOpt=xuSetTree argsMax=9999 ro=cli   [[elisp:(org-cycle)][| ]]
#+end_org """
class xuLineRun(cs.Cmnd):
    cmndParamsMandatory = [ ]
    cmndParamsOptional = [ 'xuSetTree', ]
    cmndArgsLen = {'Min': 0, 'Max': 9999,}

    @cs.track(fnLoc=True, fnEntry=True, fnExit=True)
    def cmnd(self,
             rtInv: cs.RtInvoker,
             cmndOutcome: b.op.Outcome,
             xuSetTree: typing.Optional[str]=None,  # Cs Optional Param
             argsList: typing.Optional[list[str]]=None,  # CsArgs
    ) -> b.op.Outcome:

        failed = b_io.eh.badOutcome
        callParamsDict = {'xuSetTree': xuSetTree, }
        if self.invocationValidate(rtInv, cmndOutcome, callParamsDict, argsList).isProblematic():
            return failed(cmndOutcome)
        cmndArgsSpecDict = self.cmndArgsSpec()
        xuSetTree = csParam.mappedValue('xuSetTree', xuSetTree)
####+END:
        self.cmndDocStr(f""" #+begin_org
** [[elisp:(org-cycle)][| *CmndDesc:* | ]] Run specified xuLine
        #+end_org """)

        self.captureRunStr(""" #+begin_org
#+begin_src sh :results output :session shared
  NotYet
#+end_src
#+RESULTS:
:
: OpError.Success
        #+end_org """)
        if self.justCaptureP(): return cmndOutcome

        cliArgs = self.cmndArgsGet("0&9999", cmndArgsSpecDict, argsList)

        xuName = cliArgs[0]

        try:
            xuSetTreePy = ast.literal_eval(xuSetTree)
        except (ValueError, SyntaxError) as e:
            print(f"Failed to parse xuSetTree '{xuSetTree}': {e}")
            return failed(cmndOutcome)

        xuSetTreeName = xuSetTreePy[0]

        xuSetBaseDir = xuSetTreeNameToXuSetBaseDir(xuSetTreeName)

        if xuSetBaseDir is None:
            print(f"EH.critical xuName '{xuName}' not found in {xuSetBaseDir}")
            return failed(cmndOutcome)

        xuNamePath = xuNameInXuSetBaseDir(
            xuName,
            xuSetBaseDir,
        )

        if xuNamePath is None:
            #b_io.eh.critical(f"xuName '{xuName}' not found in {xuSetBaseDir}")
            print(f"xuName '{xuName}' not found in {xuSetBaseDir}")
            return failed(cmndOutcome)

        # Create auditTrail directory structure if it doesn't exist
        import os
        from datetime import datetime
        auditTrailDir = xuNamePath / "auditTrail"
        # currentUser = os.getlogin()  # NOTYET use getpass.getuser() instead of os.getlogin()
        currentUser = "bystar"
        userAuditTrailDir = auditTrailDir / currentUser
        
        try:
            userAuditTrailDir.mkdir(parents=True, exist_ok=True)
        except Exception as e:
            b_io.eh.critical(f"Failed to create auditTrail directory {userAuditTrailDir}: {e}")
            return failed(cmndOutcome)
        
        # Create timestamp-based directory (YYYYMMDDHHMMSS format) with collision avoidance
        curTime = datetime.now().strftime("%Y%m%d%H%M%S")
        timestampAuditDir = findOrCreateDateTagDir(userAuditTrailDir, curTime)
        
        if timestampAuditDir is None:
            return failed(cmndOutcome)

        xuLineStr = ' '.join(cliArgs)

        # Get the virtual environment path for this xuSetTree
        venvPath = pathForXuSetTree(xuSetTreePy)
        
        if venvPath is None:
            return failed(cmndOutcome)

        if b.subProc.Op(outcome=cmndOutcome, log=0, cd=f"{timestampAuditDir}", uid="bystar").bash(
                f"""export PATH=$PATH:{venvPath};  {xuLineStr}""",
                stdin="",
        ).isProblematic():  return(b_io.eh.badOutcome(cmndOutcome))

        # Write audit trail files
        try:
            # Write stdout
            stdout_file = timestampAuditDir / "stdout"
            stdout_file.write_text(cmndOutcome.stdout or "")
            
            # Write stderr
            stderr_file = timestampAuditDir / "stderr"
            stderr_file.write_text(cmndOutcome.stderr or "")
            
            # Write logs (using stdout as logs)
            logs_file = timestampAuditDir / "logs"
            logs_file.write_text(cmndOutcome.stdout or "")
            
            # Write exit code
            exitCode_file = timestampAuditDir / "exitCode"
            exitCode_file.write_text(str(cmndOutcome.exitCode) if hasattr(cmndOutcome, 'exitCode') else "0")
            
            # Write command line
            cmndLine_file = timestampAuditDir / "cmndLine"
            cmndLine_file.write_text(xuLineStr)
            
            # Create empty Results directory
            results_dir = timestampAuditDir / "Results"
            results_dir.mkdir(parents=True, exist_ok=True)

        except Exception as e:
            b_io.eh.critical(f"Failed to write audit trail files in {timestampAuditDir}: {e}")
            return failed(cmndOutcome)

        results = {
            'status': 'success',
            'message': 'Operation completed successfully',
            'stdout': cmndOutcome.stdout,
            'stderr': cmndOutcome.stderr,
        }

        return cmndOutcome.set(
            # opResults=timestampAuditDir,
            opResults=results,
        )

####+BEGIN: b:py3:cs:method/args :methodName "cmndArgsSpec" :methodType "anyOrNone" :retType "bool" :deco "default" :argsList "self"
    """ #+begin_org
**  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  Mtd-T-anyOrNone [[elisp:(outline-show-subtree+toggle)][||]] /cmndArgsSpec/ deco=default  deco=default   [[elisp:(org-cycle)][| ]]
    #+end_org """
    @cs.track(fnLoc=True, fnEntry=True, fnExit=True)
    def cmndArgsSpec(self, ):
####+END:
        """  #+begin_org
** [[elisp:(org-cycle)][| *cmndArgsSpec:* | ]]
        #+end_org """

        cmndArgsSpecDict = cs.arg.CmndArgsSpecDict()
        cmndArgsSpecDict.argsDictAdd(
            argPosition="0&9999",
            argName="inputs",
            argChoices=[],
            argDescription="Rest of args for use by action"
        )

        return cmndArgsSpecDict

####+BEGIN: b:py3:cs:cmnd/classHead :cmndName "xuLinesRun" :comment "Multiple Lines from stdin as well" :extent "verify" :ro "cli" :parsMand "" :parsOpt "xuSetTree" :argsMin 0 :argsMax 9999 :pyInv "pyStdinArgs"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  CmndSvc-   [[elisp:(outline-show-subtree+toggle)][||]] <<xuLinesRun>>  *Multiple Lines from stdin as well*  =verify= parsOpt=xuSetTree argsMax=9999 ro=cli pyInv=pyStdinArgs   [[elisp:(org-cycle)][| ]]
#+end_org """
class xuLinesRun(cs.Cmnd):
    cmndParamsMandatory = [ ]
    cmndParamsOptional = [ 'xuSetTree', ]
    cmndArgsLen = {'Min': 0, 'Max': 9999,}

    @cs.track(fnLoc=True, fnEntry=True, fnExit=True)
    def cmnd(self,
             rtInv: cs.RtInvoker,
             cmndOutcome: b.op.Outcome,
             xuSetTree: typing.Optional[str]=None,  # Cs Optional Param
             argsList: typing.Optional[list[str]]=None,  # CsArgs
             pyStdinArgs: typing.Any=None,   # pyInv Argument
    ) -> b.op.Outcome:
        """Multiple Lines from stdin as well"""
        failed = b_io.eh.badOutcome
        callParamsDict = {'xuSetTree': xuSetTree, }
        if self.invocationValidate(rtInv, cmndOutcome, callParamsDict, argsList).isProblematic():
            return failed(cmndOutcome)
        cmndArgsSpecDict = self.cmndArgsSpec()
        xuSetTree = csParam.mappedValue('xuSetTree', xuSetTree)
####+END:
        self.cmndDocStr(f""" #+begin_org
** [[elisp:(org-cycle)][| *CmndDesc:* | ]] Run specified xuLine
        #+end_org """)

        self.captureRunStr(""" #+begin_org
#+begin_src sh :results output :session shared
  NotYet
#+end_src
#+RESULTS:
:
: OpError.Success
        #+end_org """)
        if self.justCaptureP(): return cmndOutcome


        def processEach(each):
            """Each is a xuLine"""
            print(f"ZZ {each} YY")

####+BEGINNOT: b:py3:func/processArgsAndStdin :comment auto-generated
        """ #+begin_org
***  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  processArgsAndStdin [[elisp:(outline-show-subtree+toggle)][||]]  =auto-generated=  [[elisp:(org-cycle)][| ]]
        #+end_org """
        if not pyStdinArgs:
            pyStdinArgs = b_io.stdin.readAsList()

        def processArgsAndStdin():
            cmndArgsSpecDict = self.cmndArgsSpec()
            if argsList is None:  # Called as pyCmnd
                cliArgs = []
            else:
                cliArgs = self.cmndArgsGet("0&9999", cmndArgsSpecDict, argsList)

            effectiveArgs = cliArgs + pyStdinArgs  # .split()

            if len(effectiveArgs) == 0:
                b_io.eh.critical_usageError(
                    "Missing Input: One of cliArgs, stdin or pyArgs; should have an input."
                )

            for each in effectiveArgs:
                processEach(each)

        processArgsAndStdin()

####+END:

        return(cmndOutcome)


####+BEGIN: b:py3:cs:method/args :methodName "cmndArgsSpec" :methodType "anyOrNone" :retType "bool" :deco "default" :argsList "self"
    """ #+begin_org
**  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  Mtd-T-anyOrNone [[elisp:(outline-show-subtree+toggle)][||]] /cmndArgsSpec/ deco=default  deco=default   [[elisp:(org-cycle)][| ]]
    #+end_org """
    @cs.track(fnLoc=True, fnEntry=True, fnExit=True)
    def cmndArgsSpec(self, ):
####+END:
        """  #+begin_org
** [[elisp:(org-cycle)][| *cmndArgsSpec:* | ]]
        #+end_org """

        cmndArgsSpecDict = cs.arg.CmndArgsSpecDict()
        cmndArgsSpecDict.argsDictAdd(
            argPosition="0&9999",
            argName="inputs",
            argChoices=[],
            argDescription="Rest of args for use by action"
        )

        return cmndArgsSpecDict


####+BEGIN: b:py3:cs:cmnd/classHead :cmndName "drf_xuLineListRun" :comment "Simulates Web UI invocation" :extent "verify" :ro "cli" :parsMand "" :parsOpt "xuSetTree" :argsMin 0 :argsMax 9999 :pyInv "pyStdinArgs"
""" #+begin_org
*  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  CmndSvc-   [[elisp:(outline-show-subtree+toggle)][||]] <<drf_xuLineListRun>>  *Simulates Web UI invocation*  =verify= parsOpt=xuSetTree argsMax=9999 ro=cli pyInv=pyStdinArgs   [[elisp:(org-cycle)][| ]]
#+end_org """
class drf_xuLineListRun(cs.Cmnd):
    cmndParamsMandatory = [ ]
    cmndParamsOptional = [ 'xuSetTree', ]
    cmndArgsLen = {'Min': 0, 'Max': 9999,}

    @cs.track(fnLoc=True, fnEntry=True, fnExit=True)
    def cmnd(self,
             rtInv: cs.RtInvoker,
             cmndOutcome: b.op.Outcome,
             xuSetTree: typing.Optional[str]=None,  # Cs Optional Param
             argsList: typing.Optional[list[str]]=None,  # CsArgs
             pyStdinArgs: typing.Any=None,   # pyInv Argument
    ) -> b.op.Outcome:
        """Simulates Web UI invocation"""
        failed = b_io.eh.badOutcome
        callParamsDict = {'xuSetTree': xuSetTree, }
        if self.invocationValidate(rtInv, cmndOutcome, callParamsDict, argsList).isProblematic():
            return failed(cmndOutcome)
        cmndArgsSpecDict = self.cmndArgsSpec()
        xuSetTree = csParam.mappedValue('xuSetTree', xuSetTree)
####+END:
        self.cmndDocStr(f""" #+begin_org
** [[elisp:(org-cycle)][| *CmndDesc:* | ]] Run specified xuLine
        #+end_org """)

        self.captureRunStr(""" #+begin_org
#+begin_src sh :results output :session shared
  NotYet
#+end_src
#+RESULTS:
:
: OpError.Success
        #+end_org """)
        if self.justCaptureP(): return cmndOutcome

        xuLineList = self.cmndArgsGet("0&9999", cmndArgsSpecDict, argsList)

        try:
            xuSetTreePy = ast.literal_eval(xuSetTree)
        except (ValueError, SyntaxError) as e:
            b_io.eh.critical(f"Failed to parse xuSetTree '{xuSetTree}': {e}")
            return failed(cmndOutcome)

        results = drf_xuLineRun(
            xuSetTreePy,
            xuLineList,
            destinations=[],
        )

        return cmndOutcome.set(
            opResults=results,
        )



####+BEGIN: b:py3:cs:method/args :methodName "cmndArgsSpec" :methodType "anyOrNone" :retType "bool" :deco "default" :argsList "self"
    """ #+begin_org
**  _[[elisp:(blee:menu-sel:outline:popupMenu)][±]]_ _[[elisp:(blee:menu-sel:navigation:popupMenu)][Ξ]]_ [[elisp:(outline-show-branches+toggle)][|=]] [[elisp:(bx:orgm:indirectBufOther)][|>]] *[[elisp:(blee:ppmm:org-mode-toggle)][|N]]*  Mtd-T-anyOrNone [[elisp:(outline-show-subtree+toggle)][||]] /cmndArgsSpec/ deco=default  deco=default   [[elisp:(org-cycle)][| ]]
    #+end_org """
    @cs.track(fnLoc=True, fnEntry=True, fnExit=True)
    def cmndArgsSpec(self, ):
####+END:
        """  #+begin_org
** [[elisp:(org-cycle)][| *cmndArgsSpec:* | ]]
        #+end_org """

        cmndArgsSpecDict = cs.arg.CmndArgsSpecDict()
        cmndArgsSpecDict.argsDictAdd(
            argPosition="0&9999",
            argName="inputs",
            argChoices=[],
            argDescription="Rest of args for use by action"
        )

        return cmndArgsSpecDict


####+BEGIN: b:py3:cs:framework/endOfFile :basedOn "classification"
""" #+begin_org
* [[elisp:(org-cycle)][| *End-Of-Editable-Text* |]] :: emacs and org variables and control parameters
#+end_org """

#+STARTUP: showall

### local variables:
### no-byte-compile: t
### end:
####+END:
