# AUTOGENERATED! DO NOT EDIT! File to edit: query.ipynb (unless otherwise specified).

__all__ = ['Querier', 'allQuery', 'ProductsFromList', 'productsFromList', 'singleProductQuery']

# Cell
import pandas as pd
from datetime import datetime
from nicHelper.wrappers import add_class_method, add_method, add_static_method
from nicHelper.dictUtil import printDict
from dataclasses_json import dataclass_json, Undefined, CatchAll
from dataclasses import dataclass
import logging
from typing import List
from s3bz.s3bz import S3
import pickle, json , boto3, zlib, os

# Cell
try:
  INVENTORY_BUCKET_NAME = os.environ['INVENTORY_BUCKET_NAME']
except Exception as e:
  print(f'missing environment variable {e} in query NB')
  INVENTORY_BUCKET_NAME = None

# Cell
class Querier:

  @staticmethod
  def validateInputQuery(keys: list, input_:dict):
    '''
      check if input query contains the valid key
      data should have the following structure
      key is a list of keys to check

      ib_prcode: String?
      ib_brcode: String?

      option, one of or both of the ib_procde must be present
    '''
    for key in keys:
      if key not in input_.keys():
        raise ValueError(f"key {key} is missing from the input")
      if not type(input_.get(key))==int:
        raise ValueError(f'key is not convertable to in {input_.get(key)}')
    return True

# Cell
@add_class_method(Querier)
def allQuery(cls, key = 'allData', bucket = os.environ.get('INVENTORY_BUCKET_NAME'), **kwargs):
  print(bucket)
  result = S3.presign(key, bucket = bucket, checkExist=False,  **kwargs)
  return result

# Cell
@dataclass_json
@dataclass
class ProductsFromList:
  cprcodes: List[str]


# Cell
import sys
@add_class_method(Querier)
def productsFromList(cls,cprcodes:List[str])->pd.DataFrame:
  db = cls.loadFromCache()
  print(f'db shape is {db.shape}')
  try:
    products = db[db['cprcode'].isin(cprcodes)]
  except:
    print(db.head())
    raise Exception(f'{db.head()} is not a valid db')
  return products

# Cell
@add_class_method(Querier)
def singleProductQuery(cls, input_)->pd.Series:
#   if not cls.validateInputQuery(['iprcode'] , input_): return f"error input {input_}"
  iprcode = int(input_['iprcode'])
  if (result:=next(cls.query(iprcode),None)): return result.toSeries()
  else: raise Exception('product not found')