# -*- 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

####+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 csxuFps_csu

from pathlib import Path
import importlib.util
from bisos.csPlayer import drf_csPlayer_pipDevBisos3

####+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:
    return
    csParams.parDictAdd(
        parName='drfExecPath',
        parDescription="Path to the drfExecutable.py file to test",
        parDataType=None,
        parDefault=f"drfExecutable.py",
        parChoices=[],
        argparseShortOpt=None,
        argparseLongOpt='--drfExecPath',
    )
    csParams.parDictAdd(
        parName='csxuDerivedBasePath',
        parDescription=f"Path to a directory containing the drfExecutable.py file",
        parDataType=None,
        parDefault=f"/bisos/var/csxu/pip_dev-bisos3/available/facter.cs/derived",
        parChoices=[],
        argparseShortOpt=None,
        argparseLongOpt='--csxuDerivedBasePath',
    )


####+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 "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

        csxuDerivedBase = "/bisos/var/csxu/pip_dev-bisos3/available/facter.cs/derived"
        drfExecPath = "drfExecutable.py"

        csxuDerivedBasePars = od([('csxuDerivedBasePath', csxuDerivedBase),])
        drfExecPathPars = od([('drfExecPath', drfExecPath),])
        allPars = od(list(csxuDerivedBasePars.items()) + list(drfExecPathPars.items()))

        cs.examples.menuChapter('=DRF Executable Testing=')

        cmnd('drfExecImport', pars=allPars)
        cmnd('drfExecShow', pars=allPars)
        cmnd('drfExecShow', pars=allPars,  comment="| pyLiteralToBash.cs -i stdinToBlack")

        return(cmndOutcome)




####+BEGIN: b:py3:cs:cmnd/classHead :cmndName "drfExecImport" :comment "" :extent "verify" :ro "cli" :parsMand "" :parsOpt "csxuDerivedBasePath drfExecPath" :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)][||]] <<drfExecImport>>  =verify= parsOpt=csxuDerivedBasePath drfExecPath ro=cli   [[elisp:(org-cycle)][| ]]
#+end_org """
class drfExecImport(cs.Cmnd):
    cmndParamsMandatory = [ ]
    cmndParamsOptional = [ 'csxuDerivedBasePath', 'drfExecPath', ]
    cmndArgsLen = {'Min': 0, 'Max': 0,}

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

        failed = b_io.eh.badOutcome
        callParamsDict = {'csxuDerivedBasePath': csxuDerivedBasePath, 'drfExecPath': drfExecPath, }
        if self.invocationValidate(rtInv, cmndOutcome, callParamsDict, None).isProblematic():
            return failed(cmndOutcome)
        csxuDerivedBasePath = csParam.mappedValue('csxuDerivedBasePath', csxuDerivedBasePath)
        drfExecPath = csParam.mappedValue('drfExecPath', drfExecPath)
####+END:

        self.cmndDocStr(f""" #+begin_org
** [[elisp:(org-cycle)][| *CmndDesc:* | ]]  Import and validate the drfExecutable.py file.
   Verifies that the generated executable can be imported and populates operationsData correctly.
        #+end_org """)

        try:
            # Resolve path: if relative, prepend csxuDerivedBasePath
            exec_file = Path(drfExecPath)
            if not exec_file.is_absolute():
                exec_file = Path(csxuDerivedBasePath) / exec_file
            
            if not exec_file.exists():
                return b_io.eh.badOutcome(cmndOutcome, f"File not found: {exec_file}")
            
            # Clear previous operationsData before importing
            drf_csPlayer_pipDevBisos3.operationsData.clear()
            
            # Import the module dynamically
            spec = importlib.util.spec_from_file_location("drfExecutable", str(exec_file))
            if spec is None or spec.loader is None:
                return b_io.eh.badOutcome(cmndOutcome, f"Could not create module spec for {exec_file}")
            
            drfExecutable = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(drfExecutable)
            
            # Check operationsData in drf_csPlayer_pipDevBisos3 (where drfExecutable populates it)
            operationsData = drf_csPlayer_pipDevBisos3.operationsData
            if not operationsData:
                return b_io.eh.badOutcome(cmndOutcome, f"operationsData is empty after import")
            
            # Validate structure
            for csxu_name, csxu_data in operationsData.items():
                if not isinstance(csxu_data, dict):
                    return b_io.eh.badOutcome(cmndOutcome, f"operationsData['{csxu_name}'] is not a dict")
                if 'description' not in csxu_data or 'parameters' not in csxu_data:
                    return b_io.eh.badOutcome(cmndOutcome, f"operationsData['{csxu_name}'] missing 'description' or 'parameters'")
            
            return cmndOutcome.set(
                opError=b.OpError.Success,
                opResults=f"Successfully imported {exec_file}. Found {len(operationsData)} CSXU entries.",
            )
            
        except Exception as e:
            return b_io.eh.badOutcome(cmndOutcome, f"Error importing drfExecutable: {e}")


####+BEGIN: b:py3:cs:cmnd/classHead :cmndName "drfExecShow" :comment "" :extent "verify" :ro "cli" :parsMand "" :parsOpt "csxuDerivedBasePath drfExecPath" :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)][||]] <<drfExecShow>>  =verify= parsOpt=csxuDerivedBasePath drfExecPath ro=cli   [[elisp:(org-cycle)][| ]]
#+end_org """
class drfExecShow(cs.Cmnd):
    cmndParamsMandatory = [ ]
    cmndParamsOptional = [ 'csxuDerivedBasePath', 'drfExecPath', ]
    cmndArgsLen = {'Min': 0, 'Max': 0,}

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

        failed = b_io.eh.badOutcome
        callParamsDict = {'csxuDerivedBasePath': csxuDerivedBasePath, 'drfExecPath': drfExecPath, }
        if self.invocationValidate(rtInv, cmndOutcome, callParamsDict, None).isProblematic():
            return failed(cmndOutcome)
        csxuDerivedBasePath = csParam.mappedValue('csxuDerivedBasePath', csxuDerivedBasePath)
        drfExecPath = csParam.mappedValue('drfExecPath', drfExecPath)
####+END:

        self.cmndDocStr(f""" #+begin_org
** [[elisp:(org-cycle)][| *CmndDesc:* | ]]  Output the operationsData from drfExecutable.py as a Python literal.
   Returns operationsData as a Python literal string that can be piped to other processors.
        #+end_org """)

        try:
            # Resolve path: if relative, prepend csxuDerivedBasePath
            exec_file = Path(drfExecPath)
            if not exec_file.is_absolute():
                exec_file = Path(csxuDerivedBasePath) / exec_file
            
            if not exec_file.exists():
                return b_io.eh.badOutcome(cmndOutcome, f"File not found: {exec_file}")
            
            # Clear previous operationsData before importing
            drf_csPlayer_pipDevBisos3.operationsData.clear()
            
            # Import the module dynamically
            spec = importlib.util.spec_from_file_location("drfExecutable", str(exec_file))
            if spec is None or spec.loader is None:
                return b_io.eh.badOutcome(cmndOutcome, f"Could not create module spec for {exec_file}")
            
            drfExecutable = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(drfExecutable)
            
            # Get operationsData from drf_csPlayer_pipDevBisos3 (where drfExecutable populates it)
            operationsData = drf_csPlayer_pipDevBisos3.operationsData
            if not operationsData:
                return b_io.eh.badOutcome(cmndOutcome, f"operationsData is empty after import")
            
            # Serialize operationsData to basic Python types (dicts, lists, strings)
            def serialize_object(obj):
                """Convert DRF objects to basic Python types"""
                # Handle Enum values - convert to their string value
                if isinstance(obj, type) and hasattr(obj, '_value_'):
                    return obj._value_
                
                if isinstance(obj, dict):
                    # Filter out special/internal attributes starting with underscore
                    return {k: serialize_object(v) for k, v in obj.items() 
                            if not k.startswith('_')}
                elif isinstance(obj, (list, tuple)):
                    return [serialize_object(item) for item in obj]
                elif hasattr(obj, '__dict__'):
                    # Convert object to dict of its attributes, filtering special ones
                    filtered_dict = {k: v for k, v in obj.__dict__.items() 
                                   if not k.startswith('_')}
                    return serialize_object(filtered_dict)
                else:
                    # Return as-is for basic types (str, int, bool, None, etc.)
                    return obj
            
            serialized = serialize_object(operationsData)
            
            # Output as Python literal string
            operationsDataLiteral = repr(serialized)
            
            return cmndOutcome.set(
                opError=b.OpError.Success,
                opResults=operationsDataLiteral,
            )
            
        except Exception as e:
            return b_io.eh.badOutcome(cmndOutcome, f"Error displaying drfExecutable: {e}")



####+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:
