#!/usr/bin/env python
"""Run S2DR4 from the command line. Needs a Gamma Earth API key in GE_API_KEY (credits are the same as S2DR3).

    python infer_s2dr4.py --date 2025-04-01 --aoi 123.7075 13.1279 123.7445 13.1641
    python infer_s2dr4.py --date 2025-04-01 --lonlat 123.726 13.146 --radius 2
"""
import os, sys, argparse, warnings
from s2dr4.inferutils import infer
from s2dr4.jobapi import S2DR4UserError
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)

os.environ.setdefault('GE_API_KEY', 'YOUR_API_KEY_HERE')

def main():
    parser = argparse.ArgumentParser(description='S2DR4: 10-band 10x super-resolution with cloud mitigation')
    parser.add_argument('--date', type=str, required=True, help='Target date, YYYY-MM-DD. The 5 most suitable images of the 180 days before it are used')
    parser.add_argument('--aoi', nargs=4, type=float, default=None, metavar=('W', 'S', 'E', 'N'), help='Bounding box AOI (longitude, latitude)')
    parser.add_argument('--lonlat', nargs=2, type=float, default=None, metavar=('LON', 'LAT'), help='Centre of a square AOI')
    parser.add_argument('--radius', type=float, default=2, help='Half side of the square AOI around --lonlat, in km (maximum 7)')
    parser.add_argument('--datapath', type=str, default='/content/datapath', help='Path for the downloaded Sentinel-2 data')
    parser.add_argument('--savepath', type=str, default='/content/output', help='Path for the super-resolved output')
    parser.add_argument('--logpath', type=str, default='/content/logs', help='Path for logging')
    parser.add_argument('-v', '--verbose', action='store_true', help='verbose output')

    args = parser.parse_args()

    key = os.getenv('GE_API_KEY')
    if not key or key == 'YOUR_API_KEY_HERE':
        # Colab: the secret GE_API_KEY is read by the module itself; elsewhere the variable is required.
        if 'COLAB_GPU' not in os.environ:
            sys.exit("ERROR: GE_API_KEY is not set. Set it to your Gamma Earth API key before running infer_s2dr4.py.")
        os.environ.pop('GE_API_KEY', None)
    if args.aoi is None and args.lonlat is None:
        parser.error('give the area: --aoi W S E N or --lonlat LON LAT')
    if args.lonlat is not None:
        args.lonlat = tuple(args.lonlat)

    try:
        infer(args)
    except S2DR4UserError as e:
        # A job the API refuses (credits, key, no image, area too large) or too few usable images:
        # the reason only, not a traceback.
        sys.exit(f'ERROR: {e}')

if __name__ == '__main__':
    main()
