from __future__ import (absolute_import, division, print_function)
from ansible import constants as C
from ansible.plugins.inventory import BaseInventoryPlugin
from ansible.errors import AnsibleError, AnsibleParserError
import os
import yaml

__metaclass__ = type

DOCUMENTATION = r'''
    name: cosmos_inventory
    plugin_type: inventory
    short_description: Returns Ansible inventory from CSV
    description: Returns Ansible inventory from CSV
    options:
      plugin:
          description: Name of the plugin
          required: true
          choices: ['cosmos_inventory']
'''

class InventoryModule(BaseInventoryPlugin):

    NAME = 'cosmos_inventory'  # used internally by Ansible, it should match the file name but not required

    def verify_file(self, path):
      '''Return true/false if this is possibly a valid file for this plugin to consume

      '''
      valid = False
      if super(InventoryModule, self).verify_file(path):
          #base class verifies that file exists 
          #and is readable by current user
          if path.endswith(('cosmos_inventory.yaml',
                            'cosmos_inventory.yml')):
              valid = True
      return valid
    
    def parse(self, inventory, loader, path, cache):
      '''Return dynamic inventory from source '''
      super(InventoryModule, self).parse(inventory, loader, path, cache)
      # Read the inventory YAML file
      self._read_config_data(path)
      try:
          # Store the options from the YAML file
          self.plugin = self.get_option('plugin')
      except Exception as e:
          raise AnsibleParserError(
              'All correct options required: {}'.format(e))
      # Call our internal helper to populate the dynamic inventory
      self._populate()

    def _populate(self):
      '''Return the hosts and groups'''
      cosmos_rules = None
      base_path = os.path.join(os.path.dirname(C.CONFIG_FILE),'..')
      with open(f'{base_path}/cosmos-rules.yaml', 'r') as file:
        cosmos_rules = yaml.safe_load(file)
      for entry in os.listdir(base_path):
        full_path = os.path.join(base_path, entry)
        if not os.path.isdir(full_path):
          continue
        if entry == 'default':
          continue
        if '.' not in entry:
          continue
        if 'README' in os.listdir(full_path):
          self.inventory.add_host(entry)