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9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
"""
Level-2 AII preprocessing


Revision History
-----------------
- [First]       2026-07-10
- [Updated]     2026-07-10

Purpose
-------
GK2A L2 AII(๋Œ€๊ธฐ ๋ถˆ์•ˆ์ • ์ง€์ˆ˜, NetCDF) ์ž๋ฃŒ๋ฅผ ์‹œ๊ฐ„(dt_str, 10๋ถ„ ๊ฐ„๊ฒฉ) ๋‹จ์œ„๋กœ ์ฝ์–ด
GK2A 2km(EA020LC) ๊ฒฉ์ž์— ๋งž์ถ˜ ๋’ค, ํ•˜๋‚˜์˜ npy(dict)๋กœ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•œ ์ „์ฒ˜๋ฆฌ ์Šคํฌ๋ฆฝํŠธ์ด๋‹ค.
satellite_radar ๋ชจ๋“ˆ์˜ ์‚ฐ์ถœ๋ฌผ๊ณผ ๋™์ผํ•œ ๊ด€์‹ฌ์˜์—ญ(bbox) crop / ํ•ด์ƒ๋„(res) ๊ฒฉ์ž๋ฅผ
์‚ฌ์šฉํ•˜๋ฏ€๋กœ, ๋‘ ์Šคํฌ๋ฆฝํŠธ์˜ npy ์‚ฐ์ถœ๋ฌผ์€ ๊ฒฉ์ž๊ฐ€ ์„œ๋กœ ์ผ์น˜ํ•œ๋‹ค.

Main Features
-------------
1. GK2A L2 AII NetCDF ์ฝ๊ธฐ ๋ฐ ๋ฌผ๋ฆฌ๊ฐ’ ๋ณต์›(_FillValue/scale_factor/add_offset ์ ์šฉ)
2. L2 ์›๋ณธ 6km(EA060LC) -> 2km(EA020LC) ์ตœ๊ทผ์ ‘ ์—…์ƒ˜ํ”Œ๋ง(LCC ํˆฌ์˜ ์ธ๋ฑ์Šค ๋งคํ•‘)
3. ์„ ํƒ์ ์œผ๋กœ 2km -> 6km ๋‹ค์šด์Šค์ผ€์ผ๋ง(3x ์ง‘๊ณ„)
4. ๋ชจ๋“  L2 ๋ณ€์ˆ˜(CAPE, KI, LI, SI, TTI)๊ฐ€ ์กด์žฌํ•  ๋•Œ๋งŒ npy ์ €์žฅ

Inputs
------
- metadata.json (CFG): ๊ฒฝ๋กœ/๋ณ€์ˆ˜/์˜์—ญ ํŒŒ๋ผ๋ฏธํ„ฐ ๋“ฑ ์‹คํ–‰ ์„ค์ •
- GK2A L2 NetCDF files: CFG["gk2a_l2_base_dir"] ์•„๋ž˜ YYYYMM/DD/HH ๊ตฌ์กฐ์— ์กด์žฌ
- Lat/Lon reference file: CFG["gk2a_ea020_latlon_file"]

Outputs
-------
- npy file: {save_dir}/res_{res}/L2/{YYYYMMDD}/l2_aii_{dt_str}.npy
  (dict ํ˜•ํƒœ: {๋ณ€์ˆ˜๋ช…: 2D array})

Usage
-----
$ python -m src.preprocess --config CONFIG.yaml

Notes
-----
- ๋ณธ ์Šคํฌ๋ฆฝํŠธ๋Š” ๋Œ€์šฉ๋Ÿ‰ ํŒŒ์ผ I/O๊ฐ€ ํฌํ•จ๋˜๋ฏ€๋กœ, ์˜ˆ์™ธ ์ฒ˜๋ฆฌ์™€ ๋กœ๊ทธ๋ฅผ ํ†ตํ•ด ๋ˆ„๋ฝ/์˜ค๋ฅ˜๋ฅผ ์ถ”์ ํ•œ๋‹ค.
- ์—…์ƒ˜ํ”Œ๋ง/๋‹ค์šด์Šค์ผ€์ผ ๊ณผ์ •์—์„œ ๊ฒฐ์ธก๊ฐ’์€ np.nan์œผ๋กœ ์œ ์ง€ํ•œ๋‹ค.
"""

from __future__ import annotations

import argparse
import json
import logging
import os
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, Optional, Tuple

import numpy as np
import pyproj
import xarray as xr
from netCDF4 import Dataset
from tqdm import tqdm


# =============================================================================
# GK2A EA060LC (6km) grid specification
# =============================================================================
# GK2A AMI East Asia Lambert Conformal Conic(LC) ํˆฌ์˜ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ฐ
# 6km(EA060LC) ๊ฒฉ์ž ์›์ /ํฌ๊ธฐ. L2 AII ํŒŒ์ผ(866 x 1000)์ด ์ด ๊ฒฉ์ž์— ์ •์˜๋˜์–ด ์žˆ๋‹ค.
_LCC_PROJ_PARAMS: Dict[str, Any] = {
    "proj": "lcc",
    "lat_1": 30,
    "lat_2": 60,
    "lat_0": 38,
    "lon_0": 126,
    "ellps": "WGS84",
}
_X0_6KM = -2997000  # 6km ๊ฒฉ์ž ์ขŒ์ƒ๋‹จ x ์ขŒํ‘œ (m)
_Y0_6KM = 2595000   # 6km ๊ฒฉ์ž ์ขŒ์ƒ๋‹จ y ์ขŒํ‘œ (m)
_RES_6KM = 6000     # 6km ๊ฒฉ์ž ๊ฐ„๊ฒฉ (m)
_NX_6KM = 1000      # 6km ๊ฒฉ์ž x ํฌ๊ธฐ
_NY_6KM = 866       # 6km ๊ฒฉ์ž y ํฌ๊ธฐ


# =============================================================================
# Argument parser
# =============================================================================
def build_parser() -> argparse.ArgumentParser:
    """
    Build CLI argument parser.

    Returns
    -------
    argparse.ArgumentParser
        Parser with arguments:
        - --config : str, path to metadata.json configuration file
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", type=str, required=False, default="../run/metadata.json")
    return parser


def parse_args_auto() -> argparse.Namespace:
    """
    Parse arguments for both interactive(Jupyter) and CLI execution.

    Returns
    -------
    argparse.Namespace
        Parsed arguments.
    """
    parser = build_parser()
    if hasattr(sys, "ps1") or "ipykernel" in sys.modules:
        args, _ = parser.parse_known_args([])
    else:
        args, _ = parser.parse_known_args()
    return args


def load_config(config_path: str) -> Dict[str, Any]:
    """
    Load JSON configuration.

    Parameters
    ----------
    config_path : str
        Path to JSON config file.

    Returns
    -------
    dict
        Configuration dictionary.

    Raises
    ------
    FileNotFoundError
        If config file does not exist.
    json.JSONDecodeError
        If config file is not a valid JSON.
    """
    with open(config_path, "r") as f:
        return json.load(f)


# =============================================================================
# Logger
# =============================================================================
def setup_logger(log_path: str) -> logging.Logger:
    """
    Set up file + stdout logger.

    Parameters
    ----------
    log_path : str
        Log file path.

    Returns
    -------
    logging.Logger
        Configured logger instance.
    """
    logger = logging.getLogger("l2_preprocess")
    logger.setLevel(logging.INFO)
    logger.handlers.clear()

    fmt = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")

    fh = logging.FileHandler(log_path)
    fh.setFormatter(fmt)
    logger.addHandler(fh)

    sh = logging.StreamHandler(sys.stdout)
    sh.setFormatter(fmt)
    logger.addHandler(sh)

    return logger


# =============================================================================
# Downscaling
# =============================================================================
def downscale_3x(arr2d: np.ndarray, agg: str = "mean", f: int = 3) -> np.ndarray:
    """
    Downscale 2D array by integer factor `f` using block aggregation.

    Parameters
    ----------
    arr2d : numpy.ndarray
        2D array (ny, nx).
    agg : str, default="mean"
        Aggregation method. One of {"mean", "max", "min", "median"}.
    f : int, default=3
        Downscale factor (e.g., f=3 for 2km->6km).

    Returns
    -------
    numpy.ndarray
        Downscaled 2D array with shape (ny//f, nx//f).

    Raises
    ------
    ValueError
        If `agg` is not supported.
    """
    ny, nx = arr2d.shape
    ny2 = (ny // f) * f
    nx2 = (nx // f) * f

    a = arr2d[:ny2, :nx2]
    a = a.reshape(ny2 // f, f, nx2 // f, f)

    if agg == "mean":
        s = np.nansum(a, axis=(1, 3))
        c = np.sum(~np.isnan(a), axis=(1, 3))
        out = s / np.where(c == 0, 1, c)
        out[c == 0] = np.nan
        return out.astype(np.float32, copy=False)

    if agg == "max":
        out = np.nanmax(np.where(np.isnan(a), -np.inf, a), axis=(1, 3))
        out[np.isneginf(out)] = np.nan
        return out.astype(np.float32, copy=False)

    if agg == "min":
        out = np.nanmin(np.where(np.isnan(a), np.inf, a), axis=(1, 3))
        out[np.isposinf(out)] = np.nan
        return out.astype(np.float32, copy=False)

    if agg == "median":
        out = np.nanmedian(a, axis=(1, 3))
        return out.astype(np.float32, copy=False)

    raise ValueError("agg must be 'mean'|'max'|'min'|'median'")


# =============================================================================
# Grid utilities
# =============================================================================
def build_index_map(
    latlon_file: str,
    bbox: Dict[str, float],
) -> Tuple[np.ndarray, np.ndarray, Tuple[int, int, int, int]]:
    """
    Build nearest-neighbour index map from 2km(EA020LC) grid to 6km(EA060LC) grid.

    ๊ด€์‹ฌ์˜์—ญ(bbox)์œผ๋กœ cropํ•œ 2km ๊ฒฉ์ž์˜ ๊ฐ ํ™”์†Œ ์œ„๊ฒฝ๋„๋ฅผ LCC ํˆฌ์˜ ์ขŒํ‘œ๋กœ ๋ณ€ํ™˜ํ•œ ๋’ค,
    ํ•ด๋‹น ์œ„์น˜์— ๋Œ€์‘ํ•˜๋Š” 6km ๊ฒฉ์ž ์ธ๋ฑ์Šค(iy, ix)๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
    L2 6km ์ž๋ฃŒ๋ฅผ arr[iy, ix]๋กœ fancy-indexing ํ•˜๋ฉด 2km ๊ฒฉ์ž๋กœ ์ตœ๊ทผ์ ‘ ์—…์ƒ˜ํ”Œ๋ง๋œ๋‹ค.

    Parameters
    ----------
    latlon_file : str
        Path to NetCDF file containing 2km grid `lon` and `lat` variables.
    bbox : dict
        Bounding box with keys:
        - lon_min, lon_max, lat_min, lat_max

    Returns
    -------
    iy : numpy.ndarray
        6km grid row indices, shape = cropped 2km grid.
    ix : numpy.ndarray
        6km grid column indices, shape = cropped 2km grid.
    crop_idx : tuple of int
        (row_min, row_max, col_min, col_max) indices used for cropping.
    """
    ds = xr.open_dataset(latlon_file)
    x = ds["lon"][:].data
    y = ds["lat"][:].data

    lon_min = bbox["lon_min"]
    lon_max = bbox["lon_max"]
    lat_min = bbox["lat_min"]
    lat_max = bbox["lat_max"]

    mask = (x >= lon_min) & (x <= lon_max) & (y >= lat_min) & (y <= lat_max)
    rows = np.any(mask, axis=1)
    cols = np.any(mask, axis=0)

    row_min, row_max = np.where(rows)[0][[0, -1]]
    col_min, col_max = np.where(cols)[0][[0, -1]]

    lon_crop = x[row_min : row_max + 1, col_min : col_max + 1]
    lat_crop = y[row_min : row_max + 1, col_min : col_max + 1]
    ds.close()

    proj = pyproj.Proj(**_LCC_PROJ_PARAMS)
    px, py = proj(lon_crop.astype("f8"), lat_crop.astype("f8"))

    ix = np.round((px - _X0_6KM) / _RES_6KM).astype(int)
    iy = np.round((_Y0_6KM - py) / _RES_6KM).astype(int)
    np.clip(ix, 0, _NX_6KM - 1, out=ix)
    np.clip(iy, 0, _NY_6KM - 1, out=iy)

    return iy, ix, (row_min, row_max, col_min, col_max)


# =============================================================================
# Data readers
# =============================================================================
def decode_var(src: Dataset, vname: str, iy: np.ndarray, ix: np.ndarray) -> np.ndarray:
    """
    Decode one L2 variable and upsample to 2km grid.

    Parameters
    ----------
    src : netCDF4.Dataset
        Opened L2 NetCDF dataset (auto mask/scale disabled).
    vname : str
        Variable name (e.g., "CAPE").
    iy, ix : numpy.ndarray
        6km grid index map from `build_index_map`.

    Returns
    -------
    numpy.ndarray
        Decoded 2D array (float32) on the cropped 2km grid.
        Missing values are np.nan.

    Notes
    -----
    - Missing flag: variable `_FillValue` attribute
    - Scaling: raw * scale_factor + add_offset
    """
    sv = src.variables[vname]
    raw = sv[:][iy, ix]
    fill = int(sv._FillValue)
    scale = float(getattr(sv, "scale_factor", 1.0))
    offset = float(getattr(sv, "add_offset", 0.0))
    valid = raw != fill
    return np.where(valid, raw.astype("f4") * scale + offset, np.nan).astype("f4")


def read_gk2a_l2(
    path: str,
    variables: list,
    iy: np.ndarray,
    ix: np.ndarray,
    logger: Optional[logging.Logger] = None,
) -> Optional[Dict[str, np.ndarray]]:
    """
    Read and decode all L2 variables from one NetCDF file.

    Parameters
    ----------
    path : str
        NetCDF file path.
    variables : list of str
        Variable names to read (e.g., ["CAPE", "KI", "LI", "SI", "TTI"]).
    iy, ix : numpy.ndarray
        6km grid index map from `build_index_map`.
    logger : logging.Logger, optional
        Logger for error reporting.

    Returns
    -------
    dict or None
        {๋ณ€์ˆ˜๋ช…: 2D array} if success, otherwise None.
    """
    try:
        with Dataset(path, "r") as src:
            src.set_auto_maskandscale(False)
            return {v: decode_var(src, v, iy, ix) for v in variables}
    except Exception as e:
        if logger:
            logger.error(f"READ_FAIL_GK2A_L2 | path={path} err={repr(e)}")
        return None


# =============================================================================
# Main
# =============================================================================
def main() -> None:
    """
    Run L2 preprocessing pipeline for given date range.

    Workflow
    --------
    For each dt_str (10-min step):
    1) Load GK2A L2 AII variables (6km) and upsample to cropped 2km grid
    2) Optionally downscale 2km -> 6km (res="6km")
    3) Save npy only if all L2 variables exist
    """
    args = parse_args_auto()

    # Script working directory: script location (for relative config path)
    script_dir = Path(__file__).resolve().parent
    os.chdir(script_dir)

    # โœ… config ๊ฒฝ๋กœ๋„ CLI์—์„œ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๊ฒŒ
    cfg = load_config(args.config)

    # โœ… ๋‚ ์งœ/ํ•ด์ƒ๋„๋Š” json์—์„œ ์ฝ์Œ
    start_date = cfg["start_date"]  # e.g., "20210701"
    end_date = cfg["end_date"]      # e.g., "20210703"
    res = cfg.get("res", "2km")     # json์— ์—†์œผ๋ฉด ๊ธฐ๋ณธ๊ฐ’

    if res not in ("2km", "6km"):
        raise ValueError(f"Invalid res: {res} (must be '2km' or '6km')")

    # Output directory
    save_dir = os.path.join(cfg["save_dir"], f"res_{res}", "L2")
    os.makedirs(save_dir, exist_ok=True)

    # Date settings
    start_dt = datetime.strptime(start_date, "%Y%m%d")
    end_dt = datetime.strptime(end_date, "%Y%m%d")
    num_days = (end_dt - start_dt).days + 1

    # Logger
    log_dir = os.path.join(save_dir, "_logs")
    os.makedirs(log_dir, exist_ok=True)
    log_path = os.path.join(log_dir, f"log_{start_date}_{end_date}.log")
    logger = setup_logger(log_path)

    logger.info(f"START | {start_date} ~ {end_date}")
    logger.info(f"save_dir={save_dir}")

    # Paths / configs
    l2_base_dir = cfg["gk2a_l2_base_dir"]
    l2_filename = cfg["l2_filename"]
    variables = cfg["l2_variables"]

    # Index map: cropped 2km grid -> 6km grid (nearest neighbour)
    iy, ix, crop_idx = build_index_map(cfg["gk2a_ea020_latlon_file"], cfg["bbox"])
    r0, r1, c0, c1 = crop_idx
    logger.info(
        f"GRID | 2km crop shape={iy.shape} (rows {r0}:{r1 + 1}, cols {c0}:{c1 + 1}) | "
        f"6km index range: iy {iy.min()}~{iy.max()}, ix {ix.min()}~{ix.max()}"
    )

    for i in tqdm(range(num_days), desc="Processing L2"):
        current_dt = start_dt + timedelta(days=i)
        ymd = current_dt.strftime("%Y%m%d")
        print(f"Processing date: {ymd}")

        for hour in range(0, 24):
            for minute in range(0, 60, 10):
                dt_str = f"{ymd}{hour:02d}{minute:02d}"

                nc_path = os.path.join(
                    l2_base_dir,
                    ymd[:6],
                    ymd[6:8],
                    f"{hour:02d}",
                    l2_filename.format(dt=dt_str),
                )

                # If file does not exist: log and skip this dt
                if not os.path.exists(nc_path):
                    logger.warning(f"MISS_GK2A_L2 | dt={dt_str} path={nc_path}")
                    continue

                # (Optional) If file is too small, treat as corrupted and skip this dt
                min_size = cfg.get("min_l2_nc_size_bytes", 0)
                if min_size and os.path.getsize(nc_path) < min_size:
                    logger.warning(
                        f"CORRUPT_L2_SMALLFILE | dt={dt_str} "
                        f"size={os.path.getsize(nc_path)} path={nc_path}"
                    )
                    continue

                # 1) Read + decode all variables (upsampled to 2km grid)
                data_dict = read_gk2a_l2(nc_path, variables, iy, ix, logger=logger)

                # If reading/decoding fails (None): log and skip this dt
                if data_dict is None:
                    logger.warning(f"SKIP_DT_L2_INCOMPLETE | dt={dt_str}")
                    continue

                # 2) Optional 2km -> 6km downscaling
                if res == "6km":
                    data_dict = {v: downscale_3x(arr, agg="mean") for v, arr in data_dict.items()}

                # 3) Save npy only if ALL required variables exist
                required = set(variables)
                if not required.issubset(data_dict.keys()):
                    missing = sorted(required - set(data_dict.keys()))
                    logger.warning(f"SKIP_SAVE_INCOMPLETE | dt={dt_str} missing={missing}")
                    continue

                day_dir = os.path.join(save_dir, ymd)
                os.makedirs(day_dir, exist_ok=True)

                save_path = os.path.join(day_dir, f"l2_aii_{dt_str}.npy")
                if os.path.exists(save_path):
                    print(f"[ Skip ]: {save_path}")
                    continue

                np.save(save_path, data_dict)
                print(f"[Saved]: {save_path}")

    print(" Done!")


if __name__ == "__main__":
    main()