#! /usr/bin/env python3
"""pop_config — generate a per-case `config.py` for p2p_processing.

Reads SAT name from argv[1] and writes `./config.py` with sensible defaults.
Replaces a 252-line, 175-print() script with one template + a small per-SAT
overrides table (v1.1.5 refactor). Output is import-compatible with
p2p_processing's `from config import ...` block (every always-required
variable is emitted; SAT-specific extras are guarded by p2p_processing's
`'<name>' in dir(config)` checks).

Usage:  pop_config SAT
"""
import sys

VALID_SATS = (
    'ERS', 'ENVI', 'ENVI_SLC', 'ALOS', 'ALOS_SLC', 'ALOS2', 'ALOS2_SCAN',
    'ALOS4', 'S1_STRIP', 'S1_TOPS', 'CSK_RAW', 'CSK_SLC', 'TSX', 'RS2', 'GF3',
    'NSR_A', 'NSR_B',
)

# Per-SAT deltas vs the base defaults. Anything not listed inherits the base.
# Empty dict = pure defaults.
SAT_OVERRIDES = {
    'ALOS':       {'shift_topo': 1},
    'ALOS_SLC':   {'shift_topo': 1, 'SLC_factor': 0.02},
    'ERS':        {'shift_topo': 1},
    'ALOS2':      {'SLC_factor': 2.0},
    'ALOS2_SCAN': {'filter_wavelength': 400, 'dec_factor': 4, 'range_dec': 4, 'azimuth_dec': 8, 'det_stitch': 0},
    # ALOS-4 (L-band, launched 2024): similar to ALOS-2 SLC defaults.
    'ALOS4':      {'SLC_factor': 2.0},
    # NSR_A / NSR_B: NISAR repeat-pass interferograms (port of p2p_processing_nsr).
    # Treated similarly to ALOS_SLC for the standard P2P stages.
    'NSR_A':      {'SLC_factor': 2.0},
    'NSR_B':      {'SLC_factor': 2.0},
    'RS2':        {'filter_wavelength': 100},
    'TSX':        {'filter_wavelength': 100},
    'S1_TOPS':    {'spec_div': 0, 'spec_mode': 1, 'range_dec': 8, 'azimuth_dec': 2, 'det_stitch': 0},
}

BASE_DEFAULTS = {
    'shift_topo':        0,
    'filter_wavelength': 200,
    'dec_factor':        2,
}

# Always-required variables (p2p_processing fails import if any are missing).
# Values here are the universal defaults; SAT overrides may replace shift_topo,
# filter_wavelength, dec_factor.
TEMPLATE = """\
#! /usr/bin/env python3
# Generated by pop_config for SAT={sat}.
# Edit any value below to override; lines starting with '#' are comments.
# Do NOT comment out a parameter with '#' to skip it — that duplicates names.

# -------- processing stage (1: preprocess ... 6: geocode) --------
proc_stage  = 1
skip_stage  = -999
skip_1      = 0
skip_2      = 0
skip_3      = 0
skip_4      = 0
skip_5      = 0
skip_6      = 0
skip_master = 0

# -------- preprocess --------
num_patches  = -999
earth_radius = -999
near_range   = -999
fd1          = -999

# -------- focus + align --------
region_cut    = -999

# -------- topo_ra --------
topo_phase       = 1
topo_interp_mode = 0
shift_topo       = {shift_topo}

# -------- interferogram + filter --------
switch_master          = 0
filter_wavelength      = {filter_wavelength}
dec_factor             = {dec_factor}
compute_phase_gradient = 0
correct_iono           = 0
iono_filt_rng          = 1.0
iono_filt_azi          = 1.0
iono_dsamp             = 1
iono_skip_est          = 1

# -------- unwrap --------
threshold_snaphu = 0
near_interp      = 0
mask_water       = 1
defomax          = 0

# -------- geocode --------
threshold_geocode = .10
"""


def render(sat):
    cfg = dict(BASE_DEFAULTS)
    cfg.update(SAT_OVERRIDES.get(sat, {}))

    body = TEMPLATE.format(
        sat=sat,
        shift_topo=cfg['shift_topo'],
        filter_wavelength=cfg['filter_wavelength'],
        dec_factor=cfg['dec_factor'],
    )

    # Append optional vars, each guarded by p2p_processing's dir(config) check.
    extras = []
    for key in ('spec_div', 'spec_mode', 'SLC_factor', 'range_dec', 'azimuth_dec', 'det_stitch'):
        if key in cfg:
            extras.append(f'{key:22s} = {cfg[key]}')
    if extras:
        body += '\n# -------- SAT-specific extras --------\n' + '\n'.join(extras) + '\n'
    return body


def pop_config():
    if len(sys.argv) != 2:
        sys.exit(f"Usage: pop_config SAT  (one of: {', '.join(VALID_SATS)})")
    sat = sys.argv[1]
    if sat not in VALID_SATS:
        print(f"WARNING: unrecognized SAT {sat!r}; using base defaults", file=sys.stderr)
    print(f"Generating config.py for {sat} ...", file=sys.stderr)
    with open('config.py', 'w') as f:
        f.write(render(sat))


if __name__ == "__main__":
    pop_config()
