#!/usr/bin/env python

import os, sys, argparse, warnings
#sys.path.append('/content/SR/src')
from s2dr3.inferutils import infer
try:
    from s2dr3.inferutils import tiles_exit_code
except ImportError:                             # wheels without the file option do not have it
    tiles_exit_code = lambda result: 0
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)

os.environ['GE_API_KEY'] = 'YOUR_API_KEY_HERE'

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--datapath', type=str, default='/content/datapath', help='Input image or folder')
    parser.add_argument('--savepath', type=str, default='/content/savepath', help='Output image or folder')
    parser.add_argument('--logpath', type=str, default='/content/logs', help='Path for logging')
    parser.add_argument('-f', '--force', action='store_true', help="force reprocessing")
    #parser.add_argument('-d', '--debug', action='store_true', help='print debugging messages')
    parser.add_argument('-v', '--verbose', action='store_true', help='verbose outout')
    parser.add_argument('-s', '--simulate', action='store_true', help='process a small simulation patch')
    parser.add_argument('-c', '--cogs', action='store_true', help='Generate COGs outputs RGB/IRP/NDVI')
    parser.add_argument('--date', type=str, default=None, help='Date')
    parser.add_argument('--date_range', type=int, default=None, help='Days before --date to look for an image (default 7, max 90). Images up to 3 days after --date are also considered')
    parser.add_argument('--max_clouds', type=int, default=None, help='Maximum cloud cover over the AOI in percent (default: no limit). If no image qualifies the run stops with an explanation')
    parser.add_argument('--b10m10', type=str, default=None, help='Direct path of the input S2L2A 10-band image')
    parser.add_argument('--aoi', nargs='+', default=None, help='AOI')
    parser.add_argument('--aoi_file', type=str, default=None, help='Vector file with the areas to process (GeoJSON, KML, KMZ, GPX, Shapefile .zip, GeoPackage, ...). The server plans the area as a parent job: one job when its box fits one hosted job, otherwise the fewest jobs of an H3 grid, each clipped to the area; the price is the area in km2 x the rate of the dearest region among its countries, rounded up (minimum 1 credit), reserved once and settled at the end (only what completes and was not already paid by this API key is charged). Prints the price and starts right away. A line becomes 150 m wide (75 m on each side), an area too thin is grown until it is 150 m wide, a point becomes a 900 m square. Limits: 2,500 km2, 400 jobs and 2,500 vertices per kind of shape (areas, points). Stops after 3 identical refusals in a row (e.g. out of credits)')
    parser.add_argument('--buffer_m', type=float, default=None, help=argparse.SUPPRESS)      # removed: kept only to say so
    parser.add_argument('--s2id', type=str, default=None, help='Exact S2 catalogue ID')
    parser.add_argument('--tile', type=int, default=640, help='Size of the processing tile')
    parser.add_argument('-b', '--batch', type=int, default=1, help='Batch size (only b=1 is supported)')

    args = parser.parse_args()
    if args.buffer_m is not None:
        parser.error('--buffer_m was removed: with --aoi_file every line is widened to 150 m (75 m on each side) and every area too thin '
                     'to hold a circle of 150 m is grown until one fits; wider areas are used as they are; a point becomes a 900 m square')

    if not os.getenv('GE_API_KEY'):
        sys.exit("ERROR: GE_API_KEY environment variable is not set. "
                "Set it to your assigned API key before running infer_s2dr3.py.")

    if args.aoi is not None: args.aoi = [float(x) for x in args.aoi]
    # Not options any more. The wheel reads these attributes directly, so they keep their old default values.
    args.mgrs = args.iso = args.NM = args.UV = None
    args.coreg, args.make_preview = False, False
    args.bands_out = 'B02 B03 B04 B05 B06 B07 B08 B8A B11 B12'.split()
    args.verbose = False
    os.makedirs(args.logpath, exist_ok=True)

    try:
        code = tiles_exit_code(infer(args))
        if code:                                # only a file run with a job that failed or was not run (1)
            sys.exit(code)
    except Exception as e:
        # A job the API refuses (no image found, not enough credits, invalid key or value) is not a crash:
        # show the reason only. Matched by name so that older wheels, which do not have this class, still work.
        if type(e).__name__ == 'JobRequestError':
            sys.exit(f'ERROR: {e}')
        raise

if __name__ == '__main__':
    main()
