#!/usr/bin/env python3

import sys
import os
import re
import inspect
from pathlib import Path

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
parentparentdir = os.path.dirname(parentdir)
sys.path.insert(0, parentparentdir)

import dumper
import getopt
import django
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'procat2.settings')
django.setup()

from markup.utils import WORKDIR, clean_path
from markup.matching import find_marked_products
from markup.spreadsheet import write_spreadsheet


def main(argv):
    def usage():
        print('usage: %s -s subdir [-d] file.pdf' % argv[0])
        return 100
    try:
        (opts, args) = getopt.getopt(argv[1:], 'd')
    except getopt.GetoptError:
        return usage()
    if not args: return usage()
    debug = 0
    subdir = 'test'
    for (k, v) in opts:
        if k == '-d': debug += 1
        elif k == '-s': subdir = v

    fname = args[0]
    path = Path(fname)
    workdir = os.path.join(WORKDIR, 'test', clean_path(path.stem))

    matches = find_marked_products(fname, workdir, debug)
    print(f'{len(matches)} product matches')
    write_spreadsheet(matches, workdir, path.stem)


if __name__ == '__main__': sys.exit(main(sys.argv))
