File size: 21,507 Bytes
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d910e3c
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d910e3c
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d910e3c
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d910e3c
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d910e3c
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442ba7e
 
 
 
b4a8f62
 
 
 
442ba7e
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442ba7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
442ba7e
 
b4a8f62
 
 
 
442ba7e
b4a8f62
442ba7e
b4a8f62
 
 
 
 
 
 
 
 
 
 
442ba7e
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
d910e3c
2c422c6
d910e3c
 
2c422c6
d910e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# ============================================================================
# IMGW Column Translation Utilities
# Maps IMGW column codes and Polish names to readable English labels.
# ============================================================================

# Master lookup: IMGW column code (lowercase, normalized) -> English label
# Derived from official IMGW format specification files:
#   s_t_format.txt, k_t_format.txt  (hourly synop, klimat)
#   s_d_format.txt, k_d_format.txt, o_d_format.txt  (daily)
#   s_m_d_format.txt, s_m_t_format.txt, k_m_d_format.txt, k_m_t_format.txt, o_m_format.txt (monthly)

IMGW_COLUMN_LOOKUP <- c(
    # --- Structural / metadata columns ---
    "station_id" = "Station ID",
    "station_name" = "Station Name",
    "nsp" = "Station ID",
    "post" = "Station Name",
    "year" = "Year",
    "rok" = "Year",
    "month" = "Month",
    "mc" = "Month",
    "miesiac" = "Month",
    "day" = "Day",
    "dz" = "Day",
    "dzien" = "Day",
    "hour" = "Hour",
    "gg" = "Hour",
    "godzina" = "Hour",
    "minute" = "Minute",
    "minuta" = "Minute",
    "date" = "Date",
    "datetime" = "Date/Time",
    "source" = "Source",
    "source_file" = "Source File",
    "resolution" = "Resolution",
    "source_rank" = "Source Rank",

    # --- Temperature ---
    "temp" = "Temp [°C]",
    "tmax" = "Max Temp [°C]",
    "tmin" = "Min Temp [°C]",
    "std" = "Mean Daily Temp [°C]",
    "stm" = "Mean Monthly Temp [°C]",
    "tmxs" = "Mean Max Temp [°C]",
    "tmns" = "Mean Min Temp [°C]",
    "tmng" = "Min Ground Temp [°C]",
    "tgmi" = "Min Ground Temp 12h [°C]",
    "ttzw" = "Wet Bulb Temp [°C]",
    "tptr" = "Dew Point [°C]",
    "tg05" = "Soil Temp 5cm [°C]",
    "tg10" = "Soil Temp 10cm [°C]",
    "tg20" = "Soil Temp 20cm [°C]",
    "tg50" = "Soil Temp 50cm [°C]",
    "tg100" = "Soil Temp 100cm [°C]",

    # --- Precipitation ---
    "smdb" = "Daily Precip [mm]",
    "summ" = "Monthly Precip [mm]",
    "opmx" = "Max Daily Precip [mm]",
    "maxo" = "Max Precip [mm]",
    "roop" = "Precip Type",
    "wo6g" = "Precip 6h [mm]",
    "ropt" = "Precip Type 6h",
    "wodz" = "Day Precip [mm]",
    "wono" = "Night Precip [mm]",
    "dn1" = "First Day Max Precip",
    "dn2" = "Last Day Max Precip",

    # --- Snow ---
    "pksn" = "Snow Depth [cm]",
    "rwsn" = "Snow Water Equiv [mm]",
    "hss" = "Fresh Snow Depth [cm]",
    "grsn" = "Snow Plot Depth [cm]",
    "gats" = "Snow Type",
    "rpsn" = "Snow Cover Type",
    "hpro" = "Sample Height [cm]",
    "cipr" = "Snow Water Reserve [mm]",
    "ukpo" = "Snow Cover Shape",

    # --- Wind ---
    "fwr" = "Wind Speed [m/s]",
    "fws" = "Mean Wind Speed [m/s]",
    "dkdk" = "Wind Dir Code",
    "krwr" = "Wind Direction [°]",
    "porw" = "Wind Gust [m/s]",
    "pork" = "Max Gust [m/s]",
    "godp" = "Gust Hour",
    "minp" = "Gust Minute",

    # --- Pressure ---
    "ppps" = "Station Pressure [hPa]",
    "pppm" = "Sea Level Pressure [hPa]",
    "tech" = "Pressure Tendency",
    "app" = "Pressure Change [hPa]",

    # --- Humidity ---
    "cpw" = "Vapour Pressure [hPa]",
    "wlgw" = "Relative Humidity [%]",
    "wlgs" = "Mean Rel Humidity [%]",
    "defi" = "Humidity Deficit [hPa]",

    # --- Clouds / Visibility ---
    "zogk" = "Total Cloud Cover [okta]",
    "nos" = "Mean Cloud Cover [okta]",
    "hpod" = "Cloud Base CL/CM [code]",
    "hpon" = "Lower Cloud Base [m]",
    "hpow" = "Upper Cloud Base [m]",
    "htxt" = "Cloud Base Text",
    "pom1" = "Instrument 1 (lower)",
    "pom2" = "Instrument 2 (upper)",
    "wid" = "Visibility [code]",
    "wido" = "Operator Visibility [m]",
    "wida" = "Auto Visibility [m]",
    "nog" = "Total Cloud Cover [okta]",
    "clcm" = "Low Cloud Cover [okta]",
    "chcl" = "Cloud CL [code]",
    "chlt" = "Cloud CL Text",
    "chcm" = "Cloud CM [code]",
    "chmt" = "Cloud CM Text",
    "chch" = "Cloud CH [code]",
    "chht" = "Cloud CH Text",

    # --- Ice / ground ---
    "twlw" = "Ice Indicator",
    "went" = "Ventilation",
    "sgrn" = "Ground State [code]",
    "sgr" = "Ground State",

    # --- Sunshine ---
    "usl" = "Sunshine [h]",
    "usln" = "Sunshine [h]",
    "suus" = "Monthly Sunshine [h]",

    # --- Weather phenomena ---
    "pogb" = "Current Weather [code]",
    "pogu" = "Past Weather [code]",
    "rosw" = "Dew Occurrence",
    "aktn" = "Actinometry [J/cm²]",

    # --- Weather phenomena durations (daily) ---
    "desz" = "Rain Duration [h]",
    "sneg" = "Snow Duration [h]",
    "disn" = "Rain+Snow Duration [h]",
    "grad" = "Hail Duration [h]",
    "mgla" = "Fog Duration [h]",
    "zmgl" = "Mist Duration [h]",
    "sadz" = "Rime Duration [h]",
    "golo" = "Glaze Duration [h]",
    "zmni" = "Low Blizzard Duration [h]",
    "zmws" = "High Blizzard Duration [h]",
    "zmet" = "Haze Duration [h]",
    "ff10" = "Wind >=10m/s Duration [h]",
    "ff15" = "Wind >15m/s Duration [h]",
    "brza" = "Thunder Duration [h]",
    "rosa" = "Dew Duration [h]",
    "szro" = "Frost Duration [h]",
    "dzps" = "Snow Cover [0/1]",
    "dzbl" = "Lightning [0/1]",
    "izd" = "Lower Isotherm [cm]",
    "izg" = "Upper Isotherm [cm]",

    # --- Weather days counts (monthly) ---
    "psdn" = "Snow Cover Days",
    "psdn" = "Snow Cover Days",
    "desd" = "Rain Days",
    "snid" = "Snow Days",
    "dsnd" = "Rain+Snow Days",
    "grdd" = "Hail Days",
    "mgld" = "Fog Days",
    "zamd" = "Mist Days",
    "sadd" = "Rime Days",
    "gold" = "Glaze Days",
    "zand" = "Low Blizzard Days",
    "zawd" = "High Blizzard Days",
    "zmed" = "Haze Days",
    "w10d" = "Wind >=10m/s Days",
    "w15d" = "Wind >15m/s Days",
    "burd" = "Thunder Days",
    "rosd" = "Dew Days",
    "szrd" = "Frost Days",
    "lds" = "Snow Precip Days",
    "ldps" = "Snow Cover Days",

    # --- Status columns (W prefix = measurement status) ---
    # We map ALL status columns to a readable format
    "wtmax" = "Status: Max Temp",
    "wtmin" = "Status: Min Temp",
    "wstd" = "Status: Mean Temp",
    "wstm" = "Status: Mean Monthly Temp",
    "wtmxs" = "Status: Mean Max Temp",
    "wwtmns" = "Status: Mean Min Temp",
    "wtmng" = "Status: Min Ground Temp",
    "wtgmi" = "Status: Min Ground 12h",
    "wtemp" = "Status: Temp",
    "wttzw" = "Status: Wet Bulb",
    "wtptr" = "Status: Dew Point",
    "wtg05" = "Status: Soil 5cm",
    "wtg10" = "Status: Soil 10cm",
    "wtg20" = "Status: Soil 20cm",
    "wtg50" = "Status: Soil 50cm",
    "wtg100" = "Status: Soil 100cm",
    "wsmdb" = "Status: Daily Precip",
    "wsumm" = "Status: Monthly Precip",
    "wopmx" = "Status: Max Precip",
    "wmaxo" = "Status: Max Precip",
    "wpksn" = "Status: Snow Depth",
    "wrwsn" = "Status: Snow Water",
    "whss" = "Status: Fresh Snow",
    "wgrsn" = "Status: Snow Plot",
    "wgats" = "Status: Snow Type",
    "wrpsn" = "Status: Snow Cover Type",
    "whpro" = "Status: Sample Height",
    "wcipr" = "Status: Snow Water Reserve",
    "wfwr" = "Status: Wind Speed",
    "wfws" = "Status: Mean Wind",
    "wdkdk" = "Status: Wind Dir",
    "wkrwr" = "Status: Wind Direction",
    "wporw" = "Status: Wind Gust",
    "wpork" = "Status: Max Gust",
    "wppps" = "Status: Station Pressure",
    "wpppm" = "Status: Sea Level Pressure",
    "wapp" = "Status: Pressure Change",
    "wcpw" = "Status: Vapour Pressure",
    "wwlgw" = "Status: Rel Humidity",
    "wwlgs" = "Status: Mean Humidity",
    "wdefi" = "Status: Humidity Deficit",
    "wzogk" = "Status: Cloud Cover",
    "wnos" = "Status: Mean Cloud Cover",
    "whpod" = "Status: Cloud Base CL/CM",
    "whpon" = "Status: Lower Cloud Base",
    "whpow" = "Status: Upper Cloud Base",
    "wwid" = "Status: Visibility",
    "wwido" = "Status: Operator Vis",
    "wwida" = "Status: Auto Visibility",
    "wnog" = "Status: Total Cloud Cover",
    "wclcm" = "Status: Low Cloud Cover",
    "wchcl" = "Status: Cloud CL",
    "wchcm" = "Status: Cloud CM",
    "wchch" = "Status: Cloud CH",
    "wsgrn" = "Status: Ground State",
    "wusl" = "Status: Sunshine",
    "wusln" = "Status: Sunshine",
    "wsuus" = "Status: Monthly Sunshine",
    "wwo6g" = "Status: Precip 6h",
    "wropt" = "Status: Precip Type 6h",
    "wwodz" = "Status: Day Precip",
    "wwono" = "Status: Night Precip",
    "wdesz" = "Status: Rain Duration",
    "wsneg" = "Status: Snow Duration",
    "wdisn" = "Status: Rain+Snow",
    "wgrad" = "Status: Hail Duration",
    "wmgla" = "Status: Fog Duration",
    "wzmgl" = "Status: Mist Duration",
    "wsadz" = "Status: Rime Duration",
    "wgolo" = "Status: Glaze Duration",
    "wzmni" = "Status: Low Blizzard",
    "wzmws" = "Status: High Blizzard",
    "wzmet" = "Status: Haze Duration",
    "wff10" = "Status: Wind >=10",
    "wff15" = "Status: Wind >15",
    "wbrza" = "Status: Thunder",
    "wrosa" = "Status: Dew",
    "wszro" = "Status: Frost",
    "wdzps" = "Status: Snow Cover",
    "wdzbl" = "Status: Lightning",
    "wizd" = "Status: Lower Isotherm",
    "wizg" = "Status: Upper Isotherm",
    "waktn" = "Status: Actinometry",
    "wrosw" = "Status: Dew Occurrence",
    "wpork" = "Status: Max Gust",
    "wpsdn" = "Status: Snow Cover Days",
    "wpsdm" = "Status: Snow Cover Days",
    "wdesd" = "Status: Rain Days",
    "wsnid" = "Status: Snow Days",
    "wdsnd" = "Status: Rain+Snow Days",
    "wgrdd" = "Status: Hail Days",
    "wmgld" = "Status: Fog Days",
    "wzamd" = "Status: Mist Days",
    "wsadd" = "Status: Rime Days",
    "wgold" = "Status: Glaze Days",
    "wzand" = "Status: Low Blizzard Days",
    "wzawd" = "Status: High Blizzard Days",
    "wzmed" = "Status: Haze Days",
    "ww10d" = "Status: Wind >=10 Days",
    "ww15d" = "Status: Wind >15 Days",
    "wburd" = "Status: Thunder Days",
    "wrosd" = "Status: Dew Days",
    "wszrd" = "Status: Frost Days",
    "wlds" = "Status: Snow Precip Days",
    "wldps" = "Status: Snow Cover Days"
)

# Position-based DATA column definitions per source_type + resolution.
# These contain ONLY the weather parameter codes (NOT structural columns
# like station_id, station_name, year, month, day, hour).
# imgw_attach_datetime already handles the structural columns.
# The data params listed here correspond to the columns that follow
# the structural ones, in the order defined by IMGW format files.
IMGW_DATA_PARAMS <- list(
    # --- HOURLY ---
    synop_hourly = c(
        "hpod", "whpod", "hpon", "whpon", "hpow", "whpow", "htxt", "pom1", "pom2",
        "wid", "wwid", "wido", "wwido", "wida", "wwida", "nog", "wnog", "krwr", "wkrwr", "fwr", "wfwr", "porw", "wporw",
        "temp", "wtemp", "ttzw", "wttzw", "went", "twlw", "cpw", "wcpw", "wlgw", "wwlgw", "tptr", "wtptr",
        "ppps", "wppps", "pppm", "wpppm", "tech", "app", "wapp",
        "wo6g", "wwo6g", "ropt", "wropt", "pogb", "pogu",
        "clcm", "wclcm", "chcl", "wchcl", "chlt", "chcm", "wchcm", "chmt", "chch", "wchch", "chht",
        "sgrn", "wsgrn", "defi", "wdefi", "usln", "wusln", "rosw", "wrosw",
        "pork", "wpork", "godp", "minp",
        "tg05", "wtg05", "tg10", "wtg10", "tg20", "wtg20", "tg50", "wtg50", "tg100", "wtg100",
        "tmin", "wtmin", "tmax", "wtmax", "tgmi", "wtgmi",
        "rwsn", "wrwsn", "pksn", "wpksn", "hss", "whss", "grsn", "wgrsn",
        "gats", "ukpo", "hpro", "whpro", "cipr", "wcipr"
    ),
    klimat_hourly = c(
        "temp", "wtemp", "ttzw", "wttzw", "twlw", "went",
        "wlgw", "wwlgw", "dkdk", "wdkdk", "fwr", "wfwr",
        "zogk", "wzogk", "wid", "wwid"
    ),

    # --- DAILY ---
    synop_daily = c(
        "tmax", "wtmax", "tmin", "wtmin", "std", "wstd", "tmng", "wtmng",
        "smdb", "wsmdb", "roop", "pksn", "wpksn", "rwsn", "wrwsn",
        "usl", "wusl",
        "desz", "wdesz", "sneg", "wsneg", "disn", "wdisn", "grad", "wgrad",
        "mgla", "wmgla", "zmgl", "wzmgl", "sadz", "wsadz", "golo", "wgolo",
        "zmni", "wzmni", "zmws", "wzmws", "zmet", "wzmet",
        "ff10", "wff10", "ff15", "wff15", "brza", "wbrza", "rosa", "wrosa", "szro", "wszro",
        "dzps", "wdzps", "dzbl", "wdzbl", "sgr",
        "izd", "wizd", "izg", "wizg", "aktn", "waktn"
    ),
    synop_daily_t = c(
        "nos", "wnos", "fws", "wfws", "temp", "wtemp", "cpw", "wcpw",
        "wlgs", "wwlgs", "ppps", "wppps", "pppm", "wpppm", "wodz", "wwodz", "wono", "wwono"
    ),
    klimat_daily = c(
        "tmax", "wtmax", "tmin", "wtmin", "std", "wstd", "tmng", "wtmng",
        "smdb", "wsmdb", "roop", "pksn", "wpksn"
    ),
    klimat_daily_t = c(
        "temp", "wtemp", "wlgs", "wwlgs", "fws", "wfws", "nos", "wnos"
    ),
    opad_daily = c(
        "smdb", "wsmdb", "roop", "pksn", "wpksn", "hss", "whss", "gats", "wgats", "rpsn", "wrpsn"
    ),

    # --- MONTHLY ---
    synop_monthly = c(
        "tmax", "wtmax", "tmxs", "wtmxs", "tmin", "wtmin", "tmns", "wwtmns", "stm", "wstm", "tmng", "wtmng",
        "summ", "wsumm", "opmx", "wopmx", "dn1", "dn2",
        "suus", "wsuus", "pksn", "wpksn", "psdn", "wpsdn",
        "desd", "wdesd", "snid", "wsnid", "dsnd", "wdsnd", "grdd", "wgrdd",
        "mgld", "wmgld", "zamd", "wzamd", "sadd", "wsadd", "gold", "wgold",
        "zand", "wzand", "zawd", "wzawd", "zmed", "wzmed",
        "w10d", "ww10d", "w15d", "ww15d", "burd", "wburd", "rosd", "wrosd", "szrd", "wszrd"
    ),
    synop_monthly_t = c(
        "nos", "wnos", "fws", "wfws", "temp", "wtemp", "cpw", "wcpw",
        "wlgs", "wwlgs", "ppps", "wppps", "pppm", "wpppm", "wodz", "wwodz", "wono", "wwono"
    ),
    klimat_monthly = c(
        "tmax", "wtmax", "tmxs", "wtmxs", "tmin", "wtmin", "tmns", "wwtmns", "stm", "wstm", "tmng", "wtmng",
        "summ", "wsumm", "opmx", "wopmx", "dn1", "dn2", "pksn", "wpksn", "psdn", "desd", "snid"
    ),
    klimat_monthly_t = c(
        "temp", "wtemp", "wlgs", "wwlgs", "fws", "wfws", "nos", "wnos"
    ),
    opad_monthly = c(
        "summ", "wsumm", "lds", "wlds", "maxo", "wmaxo", "dn1", "dn2", "ldps", "wldps"
    )
)

# Explicit mapping of IMGW measurement status codes -> paired value column code.
# Never infer status columns by grepl("^w", ...), because real parameters
# (wlgw, wlgs, wid, wido, wida, wo6g, wodz, wono, w10d, w15d, went) start with "w".
IMGW_STATUS_TO_VALUE <- c(
    "wtmax" = "tmax",
    "wtmin" = "tmin",
    "wstd" = "std",
    "wstm" = "stm",
    "wtmxs" = "tmxs",
    "wwtmns" = "tmns",
    "wtmng" = "tmng",
    "wtgmi" = "tgmi",
    "wtemp" = "temp",
    "wttzw" = "ttzw",
    "wtptr" = "tptr",
    "wtg05" = "tg05",
    "wtg10" = "tg10",
    "wtg20" = "tg20",
    "wtg50" = "tg50",
    "wtg100" = "tg100",
    "wsmdb" = "smdb",
    "wsumm" = "summ",
    "wopmx" = "opmx",
    "wmaxo" = "maxo",
    "wpksn" = "pksn",
    "wrwsn" = "rwsn",
    "whss" = "hss",
    "wgrsn" = "grsn",
    "wgats" = "gats",
    "wrpsn" = "rpsn",
    "whpro" = "hpro",
    "wcipr" = "cipr",
    "wfwr" = "fwr",
    "wfws" = "fws",
    "wdkdk" = "dkdk",
    "wkrwr" = "krwr",
    "wporw" = "porw",
    "wpork" = "pork",
    "wppps" = "ppps",
    "wpppm" = "pppm",
    "wapp" = "app",
    "wcpw" = "cpw",
    "wwlgw" = "wlgw",
    "wwlgs" = "wlgs",
    "wdefi" = "defi",
    "wzogk" = "zogk",
    "wnos" = "nos",
    "whpod" = "hpod",
    "whpon" = "hpon",
    "whpow" = "hpow",
    "wwid" = "wid",
    "wwido" = "wido",
    "wwida" = "wida",
    "wnog" = "nog",
    "wclcm" = "clcm",
    "wchcl" = "chcl",
    "wchcm" = "chcm",
    "wchch" = "chch",
    "wsgrn" = "sgrn",
    "wusl" = "usl",
    "wusln" = "usln",
    "wsuus" = "suus",
    "wwo6g" = "wo6g",
    "wropt" = "ropt",
    "wwodz" = "wodz",
    "wwono" = "wono",
    "wdesz" = "desz",
    "wsneg" = "sneg",
    "wdisn" = "disn",
    "wgrad" = "grad",
    "wmgla" = "mgla",
    "wzmgl" = "zmgl",
    "wsadz" = "sadz",
    "wgolo" = "golo",
    "wzmni" = "zmni",
    "wzmws" = "zmws",
    "wzmet" = "zmet",
    "wff10" = "ff10",
    "wff15" = "ff15",
    "wbrza" = "brza",
    "wrosa" = "rosa",
    "wszro" = "szro",
    "wdzps" = "dzps",
    "wdzbl" = "dzbl",
    "wizd" = "izd",
    "wizg" = "izg",
    "waktn" = "aktn",
    "wrosw" = "rosw",
    "wpsdn" = "psdn",
    "wpsdm" = "psdn",
    "wdesd" = "desd",
    "wsnid" = "snid",
    "wdsnd" = "dsnd",
    "wgrdd" = "grdd",
    "wmgld" = "mgld",
    "wzamd" = "zamd",
    "wsadd" = "sadd",
    "wgold" = "gold",
    "wzand" = "zand",
    "wzawd" = "zawd",
    "wzmed" = "zmed",
    "ww10d" = "w10d",
    "ww15d" = "w15d",
    "wburd" = "burd",
    "wrosd" = "rosd",
    "wszrd" = "szrd",
    "wlds" = "lds",
    "wldps" = "ldps"
)

IMGW_TRANSLATED_STATUS_TO_VALUE <- local({
    st_labels <- unname(IMGW_COLUMN_LOOKUP[names(IMGW_STATUS_TO_VALUE)])
    val_labels <- unname(IMGW_COLUMN_LOOKUP[unname(IMGW_STATUS_TO_VALUE)])
    keep <- !is.na(st_labels) & !is.na(val_labels) & !duplicated(st_labels)
    stats::setNames(val_labels[keep], st_labels[keep])
})

# Monthly phenomenon-day counts ("Liczba dni z") where status "9" means
# "no measurements of phenomena at the station" (s_m_d_format.txt) -> NA.
IMGW_MONTHLY_PHENOM_DAY_COLS_RAW <- c(
    "psdn", "desd", "snid", "dsnd", "grdd", "mgld", "zamd", "sadd", "gold",
    "zand", "zawd", "zmed", "w10d", "w15d", "burd", "rosd", "szrd", "lds", "ldps"
)
IMGW_MONTHLY_PHENOM_DAY_COLS <- unique(c(
    IMGW_MONTHLY_PHENOM_DAY_COLS_RAW,
    unname(IMGW_COLUMN_LOOKUP[IMGW_MONTHLY_PHENOM_DAY_COLS_RAW])
))

#' Assign proper IMGW column codes to headerless data frames
#'
#' After imgw_attach_datetime has named structural columns (station_id,
#' station_name, year, month, day, hour), remaining columns are still vN.
#' This function maps those vN columns sequentially to the known IMGW
#' parameter codes for the given source_type + resolution, including
#' supplementary *_t tables (s_d_t, k_d_t, s_m_t, k_m_t).
#'
#' @param df Data frame (structural cols already named, data cols as vN)
#' @param source_type Character: "synop", "klimat", or "opad"
#' @param resolution Character: "hourly", "daily", or "monthly"
#' @param csv_name Optional basename/path of CSV member inside ZIP (used to detect *_t tables)
#' @return Data frame with IMGW codes as column names
imgw_assign_column_names <- function(df, source_type, resolution, csv_name = NULL) {
    if (is.null(df) || ncol(df) == 0) {
        return(df)
    }

    current <- names(df)

    # Look up the data parameter map
    src <- tolower(trimws(source_type))
    res <- tolower(trimws(resolution))
    map_key <- paste0(src, "_", res)

    v_count <- sum(grepl("^v[0-9]+$", current))
    is_t_by_name <- !is.null(csv_name) && nzchar(csv_name) &&
        grepl("_t([_.]|$)", basename(tolower(csv_name)))
    is_t_by_width <- (res %in% c("daily", "monthly")) && (
        (identical(src, "synop") && v_count > 0L && v_count <= length(IMGW_DATA_PARAMS$synop_daily_t)) ||
        (identical(src, "klimat") && v_count > 0L && v_count <= length(IMGW_DATA_PARAMS$klimat_daily_t))
    )
    t_key <- paste0(map_key, "_t")
    if ((is_t_by_name || is_t_by_width) && !is.null(IMGW_DATA_PARAMS[[t_key]])) {
        map_key <- t_key
    }

    data_params <- IMGW_DATA_PARAMS[[map_key]]
    if (is.null(data_params)) {
        return(df)
    }

    # Some raw databases (e.g. 2025_08_o.zip) ship with internal prefixed column names
    # Examples: "kansp", "kapost", "dorok", "dosmdb", "k1rok", "k1tmax". Strip prefixes: do, ka, k1, k, s, m, ch
    for (i in seq_along(current)) {
        nm <- current[i]
        stripped <- sub("^(do|ka|k1|k|s|m|ch)", "", nm)
        if (stripped == "nsp") {
            current[i] <- "station_id"
        } else if (stripped == "post") {
            current[i] <- "station_name"
        } else if (stripped %in% c("rok", "year")) {
            current[i] <- "year"
        } else if (stripped %in% c("mc", "month", "miesiac")) {
            current[i] <- "month"
        } else if (stripped %in% c("dz", "day", "dzien")) {
            current[i] <- "day"
        } else if (stripped %in% data_params) {
            current[i] <- stripped
        }
    }

    # Find which columns are still vN (not yet named by imgw_attach_datetime)
    v_indices <- grep("^v[0-9]+$", current)
    if (length(v_indices) > 0) {
        # Map vN columns sequentially to data params
        n_to_map <- min(length(v_indices), length(data_params))
        for (j in seq_len(n_to_map)) {
            current[v_indices[j]] <- data_params[j]
        }
    }

    names(df) <- make.unique(current)
    df
}

#' Translate IMGW column names to English
#'
#' Uses the IMGW_COLUMN_LOOKUP table to translate known IMGW column codes
#' (after normalization by imgw_normalize_colnames) into readable English labels.
#' Unknown columns are left as-is.
#'
#' @param df Data frame with IMGW data (column names should already be normalized)
#' @return Data frame with renamed columns
translate_imgw_columns <- function(df) {
    if (is.null(df) || ncol(df) == 0) {
        return(df)
    }

    current_names <- names(df)
    new_names <- current_names

    # Normalize for lookup (lowercase, strip underscores for fuzzy match)
    normalized <- tolower(trimws(current_names))

    for (i in seq_along(normalized)) {
        nm <- normalized[i]

        # Direct match in lookup
        if (nm %in% names(IMGW_COLUMN_LOOKUP)) {
            new_names[i] <- IMGW_COLUMN_LOOKUP[[nm]]
            next
        }

        # Try stripping trailing _N suffix for duplicate columns (e.g. tmax_1)
        base_nm <- sub("_[0-9]+$", "", nm)
        if (base_nm != nm && base_nm %in% names(IMGW_COLUMN_LOOKUP)) {
            new_names[i] <- IMGW_COLUMN_LOOKUP[[base_nm]]
            next
        }
    }

    # Ensure uniqueness
    names(df) <- make.unique(new_names, sep = " ")
    df
}