# Path: dhis2_core/src/dhis2/core/inspect.py
# def inspect(hosts: List[HostResolved] = []):
#     for host in hosts:
#         if "dhis2" != host.type:
#             log.warning(f"Only 'dhis2' type is supported, ignoring host '{host.key}' with type '{host.type}'")
#             continue
# 
#         inspect_host(host)
# 
# Path: dhis2_core/src/dhis2/core/inventory.py
# class Inventory(BaseModel):
#     hosts: Dict[str, Host]
#     groups: Dict[str, List[str]] = Field(default_factory=dict)
# 
#     def get_many_by_id(self, ids) -> Dict[str, Host]:
#         if not isinstance(ids, (list, set, tuple)):
#             ids = [ids]
# 
#         hosts = {}
# 
#         for id in ids:  # add from self.hosts first
#             if id in self.hosts:
#                 hosts[id] = self.hosts[id]
# 
#         for id in ids:
#             if id in self.groups:
#                 for gid in self.groups[id]:
#                     if gid in self.hosts:
#                         hosts[gid] = self.hosts.get(gid)
# 
#         return hosts
# 
#     def get_one_by_id(self, id) -> Host:
#         hosts = self.get_many_by_id(id)
# 
#         if not hosts:
#             log.info("Zero hosts found for id '{id}', expected one result")
#             sys.exit(-1)
# 
#         if len(hosts) > 1:
#             log.info("Many hosts found for id '{id}', expected one result")
#             sys.exit(-1)
# 
#         return hosts[0]
# 
# def parse_file(filename: str) -> Inventory:
#     data: Dict[str, Any] = {}
# 
#     with open(filename) as f:
#         if filename.endswith(".yml"):
#             data = load(f, Loader=Loader)
#         elif filename.endswith(".json"):
#             data = json.load(f)
# 
#     return parse_obj(data)
# 
# def parse_obj(data: Dict[str, Any]) -> Inventory:
#     _process_inventory_data(data)
# 
#     try:
#         data = Inventory.parse_obj(data)
#     except ValidationError as e:
#         log.error(e.json(indent=None))
#         sys.exit(-1)
# 
#     return data
# 
# def resolve(id: str, inventory: Inventory) -> List[HostResolved]:
#     id = normalize(id)
#     id_parsed = urlparse(id)
# 
#     hosts = inventory.get_many_by_id(id_parsed.hostname)
#     host_resolved = []
# 
#     for host in hosts.items():
#         key, value = host
#         auth = None
# 
#         if id_parsed.username in value.auth:
#             auth = value.auth[id_parsed.username]
# 
#         if not auth:
#             log.error(f"No auth block with id '{id_parsed.username}'' found for host '{key}''")
#             sys.exit(-1)
# 
#         hr = HostResolved(
#             type=value.type,
#             key=key,
#             baseUrl=value.baseUrl,
#             headers=value.headers,
#             params=value.params,
#             auth=auth,
#         )
# 
#         host_resolved.append(hr)
# 
#     return host_resolved


import os
import click
import dhis2.code_list.cli as cli_code_list
import dhis2.facility_list.cli as cli_facility_list
import dhis2.generate.cli as cli_generator
import dhis2.e2b.cli as cli_e2b
from pkg_resources import iter_entry_points
from .inspect import inspect
from .inventory import Inventory, parse_file, parse_obj, resolve


@click.group()
@click.version_option()
@click.option("-i", "--inventory", metavar="INVENTORY")
@click.option("-d", "--debug", is_flag=True)
@click.pass_context
def cli(ctx, inventory, debug):
    """ DHIS2 Tool for helping with import/export of various formats. """
    ctx.obj = CliContext(inventory, debug)


@cli.command("inspect")
@click.argument("id")
@click.pass_obj
def cmd_inspect(ctx, id):
    """ Display basic dhis2 instance information """
    hosts = resolve(id, ctx.inventory)
    inspect(hosts)


@cli.group("inventory")
def cli_inventory():
    """ Various commands for working with the inventory format """
    pass


@cli_inventory.command("schema")
def cmd_inventory_schema():
    """ Generate json schema for the inventory format """

# Path: dhis2_core/src/dhis2/core/inspect.py
# def inspect(hosts: List[HostResolved] = []):
#     for host in hosts:
#         if "dhis2" != host.type:
#             log.warning(f"Only 'dhis2' type is supported, ignoring host '{host.key}' with type '{host.type}'")
#             continue
# 
#         inspect_host(host)
# 
# Path: dhis2_core/src/dhis2/core/inventory.py
# class Inventory(BaseModel):
#     hosts: Dict[str, Host]
#     groups: Dict[str, List[str]] = Field(default_factory=dict)
# 
#     def get_many_by_id(self, ids) -> Dict[str, Host]:
#         if not isinstance(ids, (list, set, tuple)):
#             ids = [ids]
# 
#         hosts = {}
# 
#         for id in ids:  # add from self.hosts first
#             if id in self.hosts:
#                 hosts[id] = self.hosts[id]
# 
#         for id in ids:
#             if id in self.groups:
#                 for gid in self.groups[id]:
#                     if gid in self.hosts:
#                         hosts[gid] = self.hosts.get(gid)
# 
#         return hosts
# 
#     def get_one_by_id(self, id) -> Host:
#         hosts = self.get_many_by_id(id)
# 
#         if not hosts:
#             log.info("Zero hosts found for id '{id}', expected one result")
#             sys.exit(-1)
# 
#         if len(hosts) > 1:
#             log.info("Many hosts found for id '{id}', expected one result")
#             sys.exit(-1)
# 
#         return hosts[0]
# 
# def parse_file(filename: str) -> Inventory:
#     data: Dict[str, Any] = {}
# 
#     with open(filename) as f:
#         if filename.endswith(".yml"):
#             data = load(f, Loader=Loader)
#         elif filename.endswith(".json"):
#             data = json.load(f)
# 
#     return parse_obj(data)
# 
# def parse_obj(data: Dict[str, Any]) -> Inventory:
#     _process_inventory_data(data)
# 
#     try:
#         data = Inventory.parse_obj(data)
#     except ValidationError as e:
#         log.error(e.json(indent=None))
#         sys.exit(-1)
# 
#     return data
# 
# def resolve(id: str, inventory: Inventory) -> List[HostResolved]:
#     id = normalize(id)
#     id_parsed = urlparse(id)
# 
#     hosts = inventory.get_many_by_id(id_parsed.hostname)
#     host_resolved = []
# 
#     for host in hosts.items():
#         key, value = host
#         auth = None
# 
#         if id_parsed.username in value.auth:
#             auth = value.auth[id_parsed.username]
# 
#         if not auth:
#             log.error(f"No auth block with id '{id_parsed.username}'' found for host '{key}''")
#             sys.exit(-1)
# 
#         hr = HostResolved(
#             type=value.type,
#             key=key,
#             baseUrl=value.baseUrl,
#             headers=value.headers,
#             params=value.params,
#             auth=auth,
#         )
# 
#         host_resolved.append(hr)
# 
#     return host_resolved


# Path: dhis2_core/src/dhis2/core/cli.py
import os
import click
import dhis2.code_list.cli as cli_code_list
import dhis2.facility_list.cli as cli_facility_list
import dhis2.generate.cli as cli_generator
import dhis2.e2b.cli as cli_e2b
from pkg_resources import iter_entry_points
from .inspect import inspect
from .inventory import Inventory, parse_file, parse_obj, resolve



@click.group()
@click.version_option()
@click.option("-i", "--inventory", metavar="INVENTORY")
@click.option("-d", "--debug", is_flag=True)
@click.pass_context
def cli(ctx, inventory, debug):
    """ DHIS2 Tool for helping with import/export of various formats. """
    ctx.obj = CliContext(inventory, debug)


@cli.command("inspect")
@click.argument("id")
@click.pass_obj
def cmd_inspect(ctx, id):
    """ Display basic dhis2 instance information """
    hosts = resolve(id, ctx.inventory)
    inspect(hosts)


@cli.group("inventory")
def cli_inventory():
    """ Various commands for working with the inventory format """
    pass


@cli_inventory.command("schema")
def cmd_inventory_schema():
    """ Generate json schema for the inventory format """

    click.echo(Inventory.schema_json(indent=2))