File size: 145,742 Bytes
7fd88a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2461d8f
7fd88a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
#!/usr/bin/env python3
"""
market_intelligence.py — RailNexus Market Intelligence Engine (v16)
Cross-references urban planning (where CAN you build) with market prices
(what is it WORTH) and projects price trends (where is it GOING).

Real APIs:
1. Catastro OVC — parcel data by address or coordinates
2. SIU WMS — land classification (urban/urbanizable/non-urbanizable)
3. Idealista API — real listings (requires API key)
4. INE API — official price indices (public, no auth)
5. Registradores — quarterly price reports

Live chain: Idealista API + INE API. Embedded reference data is historical context
only and is disabled by default for current market conclusions.

v16 corrections (v14 audit F-04/F-05 were only partially closed in v15):
- Every user-facing string comes from the TEXT catalogue (ca/es/en). v15 translated
  headers by string replacement but FeasibilityCalc, PriceProjector and risk
  descriptions were hard-coded Catalan, so ``--lang es`` / ``--lang en`` reports
  still contained "VERD — VIABLE — Marge atractiu", "Projecció composta…" etc.
- INE table 25171 mixes index levels and variation rates in sibling series.
  v15 took the FIRST series whose name contained the CCAA and summed its last
  four values as the annual growth: with the "Índice" series (~150–200) that
  yields growth of several hundred per cent. v16 selects the
  "variación trimestral" / "variación anual" series explicitly and rejects
  implausible magnitudes.
- No silent default growth. v15 fell back to ``annual_growth = 10.0`` (or the
  embedded reference) whenever INE did not answer, and still printed projections.
  v16 returns ``metodo = "no_trend_data"`` and the report says projections were
  not calculated.
- Historical reference prices (opt-in) are printed with their own data date and
  never with projections; only ``LIVE`` data yields projections/feasibility.

v16.0.1 (second correction round, driven by a live INE capture of 2026-09-15):
- The plain Tempus payload (``DATOS_TABLA/25171?nult=N``) has NO ``NombrePeriodo``
  field. Each ``Data`` record carries ``Anyo``, ``FK_Periodo`` (19..22 = T1..T4,
  verified against ``/PERIODO/{id}``), ``Fecha`` (epoch ms, period start in
  Europe/Madrid local time), ``FK_TipoDato``, ``Secreto`` and ``Valor``. v16.0.0
  read ``NombrePeriodo`` and therefore emitted ``quarter: ""`` for every record;
  the collector's ``data_date`` degraded to a bare year, which Opposition Tierra
  resolves to 31 December and which can hide up to a year of staleness.
  ``ine_period_label`` now derives the label from the fields that really exist.

v17 (third correction round, 2026-09-16 — INE cadence question from v16.0.1):
- Table 25171 was the BASE-2015 IPV table. INE re-based the index to 2025 from
  2026 T1 (INEbase notice: "A partir del primer trimestre de 2026, tanto los
  índices publicados como el histórico de la serie se presentarán en base 2025");
  25171 stopped at 2025 T4 and is no longer listed under the IPV operation
  (``TABLAS_OPERACION/IPV``). That — not INE's publication lag — is why the
  2026-09-16 snapshot dated its INE evidence "2025 T4" (~262 days, SRC-009).
  The pipeline now reads :data:`INE_IPV_TABLE` (80270, base 2025, latest 2026 T2
  on 2026-09-16, national annual variation 12.2 % = INE press note of 2026-09-07).
- The publication calendar (``PUBLICACIONFECHA_PUBLICACION/21``, 32 releases
  2019-2026) shows every quarter published 65-71 days after it ends.
  :func:`ine_cadence_assessment` compares the newest period in a payload with
  that calendar so a table that stops updating is reported as ``STALE`` by the
  collector instead of passing as ``LIVE`` until Opposition Tierra notices.
"""

import calendar
import requests
import json
import math
import xml.etree.ElementTree as ET
import sys, os as _os
sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
try:
    from catastro_idealista_real import CatastroReal, IdealistaReal, CartoCiudadGeocoder
    _REAL_MODULE = True
except ImportError:
    _REAL_MODULE = False
try:
    from agent_version import AGENT_VERSION
except ImportError:  # pragma: no cover — scripts/ always ships agent_version.py
    AGENT_VERSION = "21.3.1"
from datetime import date, datetime, timedelta
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass, asdict, field
import re
import os


# ═══════════════════════════════════════════════════════════
# CONFIGURATION
# ═══════════════════════════════════════════════════════════

# Idealista API credentials (set as environment variables)
IDEALISTA_API_KEY = os.environ.get("IDEALISTA_API_KEY", "")
IDEALISTA_API_SECRET = os.environ.get("IDEALISTA_API_SECRET", "")

# Reference construction costs by region (CSCAE 2025, €/m²)
CONSTRUCTION_COSTS = {
    "default": 1450,
    "madrid": 1600,
    "barcelona": 1550,
    "valencia": 1450,
    "sevilla": 1350,
    "bilbao": 1500,
    "malaga": 1400,
}

# CCAA codes for INE API
INE_CCAA_CODES = {
    "andalucia": "01", "aragon": "02", "asturias": "03",
    "baleares": "04", "canarias": "05", "cantabria": "06",
    "castilla_leon": "07", "castilla_mancha": "08",
    "cataluña": "09", "valencia": "10", "extremadura": "11",
    "galicia": "12", "madrid": "13", "murcia": "14",
    "navarra": "15", "pais_vasco": "16", "rioja": "17",
    "ceuta": "18", "melilla": "19", "nacional": "00",
}

# Province to CCAA mapping (most populated)
PROVINCE_TO_CCAA = {
    "barcelona": "cataluña", "tarragona": "cataluña",
    "girona": "cataluña", "lleida": "cataluña",
    "valencia": "valencia", "alicante": "valencia",
    "castellon": "valencia", "castelló": "valencia",
    "madrid": "madrid",
    "sevilla": "andalucia", "malaga": "andalucia",
    "granada": "andalucia", "cordoba": "andalucia",
    "cadiz": "andalucia", "almeria": "andalucia",
    "jaen": "andalucia", "huelva": "andalucia",
    "vizcaya": "pais_vasco", "guipuzcoa": "pais_vasco",
    "alava": "pais_vasco",
    "zaragoza": "aragon", "huesca": "aragon", "teruel": "aragon",
    "a coruña": "galicia", "pontevedra": "galicia",
    "ourense": "galicia", "lugo": "galicia",
    "murcia": "murcia",
    "palma de mallorca": "baleares", "mallorca": "baleares",
    "las palmas": "canarias", "tenerife": "canarias",
    "navarra": "navarra", "pamplona": "navarra",
}

# How INE names each CCAA inside the IPV table series names (lower-case, accents
# stripped by _normalize; identical layout in 80270 and in the legacy 25171).
# Used to pick the right series; v15 matched the raw CCAA key ("pais_vasco",
# "castilla_leon") which never matched the INE label.
INE_CCAA_LABELS = {
    "andalucia": "andalucia", "aragon": "aragon", "asturias": "asturias",
    "baleares": "balears", "canarias": "canarias", "cantabria": "cantabria",
    "castilla_leon": "castilla y leon", "castilla_mancha": "castilla - la mancha",
    "cataluña": "cataluna", "valencia": "comunitat valenciana",
    "extremadura": "extremadura", "galicia": "galicia", "madrid": "madrid",
    "murcia": "murcia", "navarra": "navarra", "pais_vasco": "pais vasco",
    "rioja": "rioja", "ceuta": "ceuta", "melilla": "melilla", "nacional": "nacional",
}

# Plausibility bound for a quarterly/annual % variation of a housing price index.
MAX_PLAUSIBLE_VARIATION_PCT = 50.0

# ─── Colegio de Registradores — real notarized transaction prices (v18) ──────
# Verified live 2026-09-16: opendata.registradores.org (linked from "Portal de
# datos abiertos" on the official Portal Estadístico Registral) publishes
# "Compraventas de inmuebles, uso residencial" as a flat CSV covering 2007
# through the latest published quarter, one row per (year, quarter, CCAA or
# province). Real notarized sale price per m² (``viv-pm2``) — NOT an index and
# NOT an asking price; this is the "transaction_price" role opposition_tierra.py
# already anticipates (SRC-010 ``price_roles``). Filename embeds the coverage
# end and therefore changes every quarter; do not pin the quarter in the URL
# beyond what was verified (2007-2t2026 = through 2026 T2, published by
# 2026-09-16).
REGISTRADORES_COMPRAVENTAS_URL = (
    "https://opendata.registradores.org/data-integration/"
    "compraventas-residencial-trimestres-provincias-es/RP_ComprvResid_2007-2t2026.csv"
)
# v18 round 5 hardening (verified live 2026-09-16): the directory listing is
# WAF-403 and there is no "latest" alias, so the pinned URL will answer 404 the
# day 2026 T3 is published. The dataset page below links the current CSV/ODS/
# XLSX file names (three ``RP_ComprvResid_2007-<q>t<yyyy>.*`` hrefs); when the
# pinned URL fails, the collector reads that page and follows the newest CSV.
REGISTRADORES_DATASET_PAGE = (
    "https://opendata.registradores.org/dataset/dataset/"
    "compraventas-de-inmuebles-uso-residencial-por-provincia"
)
REGISTRADORES_CSV_URL_PATTERN = (
    r"https://opendata\.registradores\.org/data-integration/"
    r"compraventas-residencial-trimestres-provincias-es/RP_ComprvResid_\d{4}-([1-4])t(\d{4})\.csv"
)
# Columns the collector relies on; any other column may come and go.
REGISTRADORES_REQUIRED_COLUMNS = ("ano", "trim", "geo", "ca", "viv-pm2")
# Publication cadence: ONE live observation so far (2026 T2 on the portal by
# 2026-09-16 = 78 days after the quarter closed). Until more releases are
# observed the slack is generous: a quarter is expected 100 days after it ends.
REGISTRADORES_PUBLICATION_LAG_DAYS = 100


def discover_registradores_csv_url(html: str) -> str:
    """Return the newest ``RP_ComprvResid_*.csv`` URL linked in the dataset page (pure).

    Several files may be linked (current and, during a transition, previous
    quarter); the one with the highest ``(year, quarter)`` wins. ``""`` when
    the page links no CSV of that family (schema/portal change).
    """
    best: Optional[Tuple[int, int, str]] = None
    for match in re.finditer(REGISTRADORES_CSV_URL_PATTERN, html or ""):
        key = (int(match.group(2)), int(match.group(1)), match.group(0))
        if best is None or key > best:
            best = key
    return best[2] if best else ""


def registradores_expected_latest_quarter(today: Optional[date] = None) -> Tuple[int, int]:
    """``(year, quarter)`` the Registradores portal should have published by ``today``."""
    today = today or date.today()
    year, quarter = today.year, (today.month - 1) // 3 + 1
    for _ in range(8):
        quarter -= 1
        if quarter == 0:
            year, quarter = year - 1, 4
        end_month = quarter * 3
        quarter_end = date(year, end_month, calendar.monthrange(year, end_month)[1])
        if quarter_end + timedelta(days=REGISTRADORES_PUBLICATION_LAG_DAYS) <= today:
            return year, quarter
    return year, quarter


def registradores_cadence_assessment(latest_label: str, today: Optional[date] = None) -> Dict:
    """``CURRENT`` / ``STALE`` / ``UNKNOWN`` for the newest Registradores quarter (pure).

    Same contract as :func:`ine_cadence_assessment`; ``STALE`` means the file
    the collector read stops at least one quarter before what the (single-
    observation) calendar expects — e.g. the pinned filename kept serving an
    old file, or the portal stopped updating.
    """
    today = today or date.today()
    exp_year, exp_q = registradores_expected_latest_quarter(today)
    expected = f"{exp_year} T{exp_q}"
    base = {"latest": latest_label or "", "expected_latest": expected,
            "publication_lag_days": REGISTRADORES_PUBLICATION_LAG_DAYS}
    match = re.fullmatch(r"(\d{4})\s*T([1-4])", (latest_label or "").strip().upper())
    if not match:
        return {**base, "quarters_behind": None, "assessment": "UNKNOWN",
                "note": "latest period could not be parsed; cannot compare with the expected calendar"}
    behind = (exp_year * 4 + exp_q) - (int(match.group(1)) * 4 + int(match.group(2)))
    if behind <= 0:
        return {**base, "quarters_behind": max(behind, 0), "assessment": "CURRENT",
                "note": (f"latest period {latest_label} is what the Registradores calendar allows on "
                         f"{today.isoformat()} (one observation: T2 available 78 days after quarter end; "
                         f"slack {REGISTRADORES_PUBLICATION_LAG_DAYS} days)")}
    return {**base, "quarters_behind": behind, "assessment": "STALE",
            "note": (f"{expected} was expected by {today.isoformat()} but the dataset stops at "
                     f"{latest_label} ({behind} quarter(s) behind): the file read is not the current one")}
# The static-asset host answers "Request Rejected" (WAF block, HTTP 200 with an
# HTML error body) to the project's own RailNexus User-Agent (HTTP_HEADERS in
# legal_monitor.py) but 200 text/csv to a plain browser UA; verified live both
# ways on 2026-09-16. This header override is scoped to this one collector.
REGISTRADORES_HEADERS = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
                  "(KHTML, like Gecko) Chrome/128.0 Safari/537.36",
    "Accept": "text/csv,*/*",
}
# How the Registradores CSV names each CCAA in its own ``ca`` column (verified
# live 2026-09-16 — the file's actual distinct values). Accented, exact-match;
# deliberately NOT reused from INE_CCAA_LABELS, which is normalized/lower-cased
# for substring search against INE series NAMES, a different matching problem.
REGISTRADORES_CCAA_NAMES = {
    "andalucia": "Andalucía", "aragon": "Aragón", "asturias": "Principado de Asturias",
    "baleares": "Illes Balears", "canarias": "Canarias", "cantabria": "Cantabria",
    "castilla_leon": "Castilla y León", "castilla_mancha": "Castilla-La Mancha",
    "cataluña": "Cataluña", "valencia": "Comunitat Valenciana",
    "extremadura": "Extremadura", "galicia": "Galicia", "madrid": "Comunidad de Madrid",
    "murcia": "Región de Murcia", "navarra": "C. Foral de Navarra",
    "pais_vasco": "País Vasco", "rioja": "La Rioja", "ceuta": "Ceuta",
    "melilla": "Melilla", "nacional": "ESPAÑA",
}

# INE Tempus period identifiers for quarters. Verified live on 2026-09-15 against
# https://servicios.ine.es/wstempus/js/ES/PERIODO/{id}:
#   19 -> {"Nombre": "T1", "Valor": 1, "Mes_inicio": "1",  "FK_Periodicidad": 3}
#   20 -> {"Nombre": "T2", "Valor": 2, "Mes_inicio": "4",  ...}
#   21 -> {"Nombre": "T3", "Valor": 3, "Mes_inicio": "7",  ...}
#   22 -> {"Nombre": "T4", "Valor": 4, "Mes_inicio": "10", ...}
# Only these four ids were verified; anything else falls back to the ``Fecha``
# field rather than to a guessed table.
INE_QUARTER_PERIOD_IDS = {19: "T1", 20: "T2", 21: "T3", 22: "T4"}

# INE IPV table ids (Tempus ``DATOS_TABLA/{id}``). Verified live 2026-09-16:
# - 80270 "Índices por CCAA: general, vivienda nueva y de segunda mano.
#   Trimestrales" — base 2025, listed by the IPV operation (TABLAS_OPERACION/IPV,
#   publicación 21, periodicidad trimestral), last modified 2026-09-07 09:00 CEST
#   = the calendar release of 2026 T2; latest period 2026 T2; 240 series with the
#   same names/CCAA labels as 25171 (Índice / Variación trimestral / Variación
#   anual / Variación en lo que va de año). 79563 exposes the same series ids.
# - 25171 is the BASE-2015 table used by v13..v16.0.1: it stops at 2025 T4 and
#   is not listed under the operation any more. Kept only as a documented legacy
#   id; nothing in the pipeline requests it.
INE_IPV_TABLE = "80270"
INE_IPV_TABLE_LEGACY_BASE2015 = "25171"
INE_IPV_BASE_YEAR = "2025"

# v19 (B4): housing sales COUNTS come from the ETDP operation (Estadística de
# Transmisiones de Derechos de la Propiedad, operation id 7, publication 28).
# ``TABLAS_OPERACION/ETDP`` (live 2026-09-16) lists 6150 "Compraventa de
# viviendas según régimen y estado", coverage NAC-CCAA-PROV, monthly
# (FK_Periodicidad 1), from 2007, last modified 2026-08-07 = the release of
# June 2026; the payload has 360 series (national + 19 CCAA + 52 provinces x
# General / Vivienda nueva / segunda mano / libre / protegida), FK_Periodo =
# month number (PERIODO/6 = "Junio"). 6155 / 49280 are the annual variants.
# The ids v13..v18 carried (6171 "transactions", 3459 "avg price m2") answer
# HTTP 404 and never existed in this catalogue; 3459 is removed outright
# (Registradores and MIVAU cover price per m2), 6171 is replaced by 6150.
INE_ETDP_COMPRAVENTAS_TABLE = "6150"
INE_ETDP_DEAD_TABLE_TRANSACTIONS = "6171"   # documented dead id, never requested
INE_MONTH_PERIOD_IDS = {i: f"M{i:02d}" for i in range(1, 13)}   # PERIODO/1..12 = enero..diciembre

# v19 P0: label of a land-classification record that carries ONLY city-wide
# aggregate figures. Any consumer/template must treat it as "not verified for
# this parcel" (``LandClassification.verified_for_parcel`` is False and both
# ``permite_*`` are None on such a record — enforced by ``__post_init__``).
SIU_UNVERIFIED_SOURCE = ("SIU (sin verificar — dato de referencia agregado por ciudad, "
                         "no por parcela)")

# v19: the real per-point zoning services (live-verified 2026-09-16, see
# live_verification/probe_log_2026-09-16_r6.txt).
#
# SIU (Sistema de Información Urbana, MIVAU). The visor at
# mapas.fomento.gob.es/VisorSIU is an ArcGIS app; its data lives in the ArcGIS
# REST folder ``/arcgis/rest/services/SIU``. The OGC WMS façade of the same
# server (``.../MapServer/WMSServer``, the endpoint the IDEE catalogue lists)
# answers HTTP 400/499, so the working GetFeatureInfo equivalent is the REST
# ``identify`` operation on the map services the visor itself draws:
# - ``CLASES_DE_SUELO``: one polygon layer, field ``ClaseSuelo`` with exactly
#   six values (queried with returnDistinctValues): SUELO URBANO, SUELO URBANO
#   NO CONSOLIDADO, SUELO URBANIZABLE DELIMITADO O SECTORIZADO, SUELO
#   URBANIZABLE NO DELIMITADO O SECTORIZADO, SUELO NO URBANIZABLE, SISTEMAS
#   GENERALES Y OTROS. Verified: Puerta del Sol -> SUELO URBANO; the Retiro
#   park -> SISTEMAS GENERALES Y OTROS; Rascafría (sierra) -> SUELO NO
#   URBANIZABLE; Plaça Catalunya -> SUELO URBANO; Paris / open sea -> 0 results.
# - ``Planeamiento_Vigente``: municipality polygons with ``FiguraVigente`` /
#   ``FechaFigura`` (e.g. Madrid "Plan General" 1997) and the regional viewer
#   link. Municipal-level, used only for ``plan_vigente``.
# The SIU has the CLASS of land (clasificación) but NOT the USE (calificación:
# residential / industrial / green ...): that lives in each municipal plan.
SIU_ARCGIS_ROOT = "https://mapas.fomento.gob.es/arcgis/rest/services/SIU"
SIU_CLASES_SUELO_MAPSERVER = SIU_ARCGIS_ROOT + "/CLASES_DE_SUELO/MapServer"
SIU_PLANEAMIENTO_MAPSERVER = SIU_ARCGIS_ROOT + "/Planeamiento_Vigente/MapServer"
SIU_VERIFIED_SOURCE = "SIU (MIVAU) — identify en CLASES_DE_SUELO, mapas.fomento.gob.es/arcgis"
# ClaseSuelo -> (permite_construccion, clase_suelo key, note). The two
# "urbanizable" classes admit building only after the development plan and
# urbanisation the class requires; the note says so and FeasibilityCalc adds a
# risk. Any value outside this table is reported verified-but-undecided
# (permite_construccion None), never mapped by resemblance.
SIU_CLASE_SUELO_VERDICT = {
    "SUELO URBANO": (True, "suelo_urbano", ""),
    "SUELO URBANO NO CONSOLIDADO": (True, "suelo_urbano_no_consolidado",
                                    "requiere completar la urbanización / gestión previa"),
    "SUELO URBANIZABLE DELIMITADO O SECTORIZADO": (
        True, "suelo_urbanizable_delimitado",
        "edificable solo tras el plan parcial/de sectorización y la urbanización"),
    "SUELO URBANIZABLE NO DELIMITADO O SECTORIZADO": (
        False, "suelo_urbanizable_no_delimitado",
        "no edificable hasta su delimitación/sectorización por un plan"),
    "SUELO NO URBANIZABLE": (False, "suelo_no_urbanizable", ""),
    "SISTEMAS GENERALES Y OTROS": (False, "sistemas_generales",
                                   "sistema general (parque, infraestructura, equipamiento público)"),
}

# MUC (Mapa urbanístic de Catalunya, Departament de Territori). Real WMS at
# sig.gencat.cat/ows/MUC/wms (GetCapabilities: 31 queryable layers, JSON
# GetFeatureInfo). The "MUCVW_MUCS_*" layers are the synthesis of every
# municipal plan; GetFeatureInfo in EPSG:3857 returns the polygon under the
# point. Verified: Plaça Catalunya -> CLAS "SUC Sòl urbà" + QUAL "SX1 Sistema
# viari: eixos estructurants"; Parc Güell -> QUAL "SV Parcs i jardins urbans";
# Sabadell town hall -> "SE Equipament administratiu". (The "MUCPD_*" layers —
# planejament derivat — returned nothing at those points and are not used.)
# Qualification codes and meanings come from the MUC's own open dataset
# ``epsm-zskb`` column metadata (R1..R6 residential, A1..A3 economic activity,
# M1..M3 transformation, S* systems, N1..N4 non-developable).
MUC_WMS_URL = "https://sig.gencat.cat/ows/MUC/wms"
MUC_LAYER_CLASSIFICATION = "MUCVW_MUCS_CLAS"
MUC_LAYER_QUALIFICATION = "MUCVW_MUCS_QUAL"
MUC_BBOX_WGS84 = (0.06, 40.51, 3.34, 42.89)   # min lon, min lat, max lon, max lat (from capabilities)
MUC_VERIFIED_SOURCE = "MUC — Mapa urbanístic de Catalunya (WMS GetFeatureInfo, sig.gencat.cat)"
MUC_CLASS_KEYS = {"SUC": "suelo_urbano", "SNC": "suelo_urbano_no_consolidado",
                  "SUD": "suelo_urbanizable_delimitado", "SND": "suelo_urbanizable_no_delimitado",
                  "SNU": "suelo_no_urbanizable"}
# qualification code prefix -> (permite_construccion, permite_residencial, calificacion)
MUC_QUAL_VERDICT = {
    "R": (True, True, "residencial"),
    "A": (True, False, "actividad económica"),
    "M": (True, None, "transformación / mixto"),
    "S": (False, False, "sistema"),
    "N": (False, False, "no urbanizable"),
}


def muc_qualification_verdict(code: str) -> Tuple[Optional[bool], Optional[bool], str]:
    """Map a MUC qualification code (``R1``, ``A2``, ``SX1``, ``SV``, ``N2``...) to
    ``(permite_construccion, permite_residencial, calificacion)`` (pure).

    Unknown or empty codes give ``(None, None, "")``: verified point, undecided
    verdict — never a guess by resemblance.
    """
    code = (code or "").strip().upper()
    if not code:
        return None, None, ""
    verdict = MUC_QUAL_VERDICT.get(code[0])
    if verdict is None:
        return None, None, ""
    return verdict


def siu_clase_suelo_verdict(clase: str) -> Tuple[Optional[bool], str, str]:
    """Map a SIU ``ClaseSuelo`` value to ``(permite_construccion, clase_suelo, note)`` (pure)."""
    key = re.sub(r"\s+", " ", (clase or "").strip().upper())
    return SIU_CLASE_SUELO_VERDICT.get(key, (None, _normalize(key).replace(" ", "_"), ""))


def web_mercator(lat: float, lon: float) -> Tuple[float, float]:
    """WGS84 -> EPSG:3857 metres (pure; the MUC WMS is queried in that CRS)."""
    x = lon * 20037508.34 / 180.0
    y = math.log(math.tan((90.0 + lat) * math.pi / 360.0)) / (math.pi / 180.0) * 20037508.34 / 180.0
    return x, y

# Publication cadence of the IPV, from the Tempus calendar
# ``PUBLICACIONFECHA_PUBLICACION/21`` (32 releases, 2019-03-08 .. 2026-12-04): a
# quarter is published 65-71 days after it ends (T4 -> early March, T1 -> early
# June, T2 -> early September, T3 -> early December). A quarter is therefore
# EXPECTED once ``quarter_end + INE_IPV_PUBLICATION_LAG_DAYS`` has passed; the
# 4-day slack over the observed maximum absorbs a release shifted by a holiday
# without hiding a table that stopped updating (at least one full quarter behind).
# Consequence for Opposition Tierra: with this cadence the newest expected
# quarter is at most 168 days old (dated to day 28 of its last month, e.g. T1
# on 2026-09-12, the day before T2 becomes due), so the default SRC-009
# threshold of 180 days never fires on a table that INE is actually updating.
# SRC-009 on INE data means a stale table.
INE_IPV_PUBLICATION_LAG_DAYS = 75
INE_IPV_OBSERVED_LAG_DAYS = (65, 71)


def ine_expected_latest_quarter(today: Optional[date] = None) -> Tuple[int, int]:
    """Return ``(year, quarter)`` of the newest IPV quarter INE should have published.

    Walks back from the quarter containing ``today`` until it finds a quarter
    whose end plus :data:`INE_IPV_PUBLICATION_LAG_DAYS` is on or before
    ``today``. Examples (lag 75): 2026-09-16 -> (2026, 2); 2026-09-12 ->
    (2026, 1) (T2 is only expected from 2026-09-13); 2027-01-01 -> (2026, 3).
    """
    today = today or date.today()
    year, quarter = today.year, (today.month - 1) // 3 + 1
    for _ in range(8):
        quarter -= 1
        if quarter == 0:
            year, quarter = year - 1, 4
        end_month = quarter * 3
        quarter_end = date(year, end_month, calendar.monthrange(year, end_month)[1])
        if quarter_end + timedelta(days=INE_IPV_PUBLICATION_LAG_DAYS) <= today:
            return year, quarter
    return year, quarter


def ine_cadence_assessment(latest_label: str, today: Optional[date] = None) -> Dict:
    """Compare the newest period of an INE payload with the IPV publication calendar.

    Returns ``{"latest", "expected_latest", "quarters_behind", "assessment",
    "publication_lag_days", "note"}`` where ``assessment`` is ``CURRENT`` (the
    table is as new as the calendar allows), ``STALE`` (at least one quarter
    that INE has already published is missing — the table is not being updated,
    e.g. a base change moved the series to another table id) or ``UNKNOWN``
    (no parseable ``YYYY Tn`` label). Pure function; ``today`` is injectable.
    """
    today = today or date.today()
    exp_year, exp_q = ine_expected_latest_quarter(today)
    expected = f"{exp_year} T{exp_q}"
    lo, hi = INE_IPV_OBSERVED_LAG_DAYS
    base = {"latest": latest_label or "", "expected_latest": expected,
            "publication_lag_days": INE_IPV_PUBLICATION_LAG_DAYS}
    match = re.fullmatch(r"(\d{4})\s*T([1-4])", (latest_label or "").strip().upper())
    if not match:
        return {**base, "quarters_behind": None, "assessment": "UNKNOWN",
                "note": "latest period could not be parsed; cannot compare with the INE calendar"}
    year, quarter = int(match.group(1)), int(match.group(2))
    behind = (exp_year * 4 + exp_q) - (year * 4 + quarter)
    if behind <= 0:
        return {**base, "quarters_behind": max(behind, 0), "assessment": "CURRENT",
                "note": (f"latest period {latest_label} is what the INE calendar allows on "
                         f"{today.isoformat()} (quarters are published {lo}-{hi} days after they end)")}
    return {**base, "quarters_behind": behind, "assessment": "STALE",
            "note": (f"the INE calendar expects {expected} to be published by {today.isoformat()}; "
                     f"this table stops at {latest_label} ({behind} quarter(s) behind). The table "
                     f"is not being updated (base change / discontinued table id) — this is NOT "
                     f"the normal INE publication lag of {lo}-{hi} days")}


def ine_period_label(record: Dict) -> str:
    """Return the period label (``T1``..``T4``) of one INE Tempus ``Data`` record.

    Resolution order, all observed on the live service (2026-09-15):
    1. ``T3_Periodo`` — present only when the table is requested with ``tip=A``.
    2. ``NombrePeriodo`` — never seen live; kept so older fixtures keep working.
    3. ``FK_Periodo`` via :data:`INE_QUARTER_PERIOD_IDS` (plain payload).
    4. ``Fecha`` (epoch milliseconds, period start at 00:00 Europe/Madrid, hence
       22:00/23:00 UTC of the previous day): shift by 12 hours before reading the
       month so 2024-12-31T23:00Z resolves to January -> ``T1``.
    Returns ``""`` when nothing usable exists; callers must treat that as
    "period unknown", never as a valid label.
    """
    if not isinstance(record, dict):
        return ""
    for key in ("T3_Periodo", "NombrePeriodo"):
        label = record.get(key)
        if isinstance(label, str) and label.strip():
            return label.strip()
    period_id = record.get("FK_Periodo")
    try:
        period_id = int(period_id)
    except (TypeError, ValueError):
        period_id = None
    if period_id in INE_QUARTER_PERIOD_IDS:
        return INE_QUARTER_PERIOD_IDS[period_id]
    if period_id in INE_MONTH_PERIOD_IDS:          # v19: monthly tables (ETDP 6150)
        return INE_MONTH_PERIOD_IDS[period_id]
    fecha = record.get("Fecha")
    if isinstance(fecha, (int, float)) and fecha > 0:
        try:
            from datetime import timezone as _tz
            start = datetime.fromtimestamp(fecha / 1000.0, tz=_tz.utc) + timedelta(hours=12)
            return f"T{(start.month - 1) // 3 + 1}"
        except (OverflowError, OSError, ValueError):
            return ""
    return ""


def ine_period_start_iso(record: Dict) -> str:
    """Return the period start date (``YYYY-MM-DD``) from ``Fecha``, or ``""``.

    Applies the same 12-hour shift as :func:`ine_period_label` so the Madrid
    midnight encoded as previous-day UTC lands on the first day of the period.
    """
    fecha = record.get("Fecha") if isinstance(record, dict) else None
    if isinstance(fecha, (int, float)) and fecha > 0:
        try:
            from datetime import timezone as _tz
            start = datetime.fromtimestamp(fecha / 1000.0, tz=_tz.utc) + timedelta(hours=12)
            return start.strftime("%Y-%m-%d")
        except (OverflowError, OSError, ValueError):
            return ""
    if isinstance(fecha, str) and len(fecha) >= 10:
        return fecha[:10]
    return ""


def registradores_period_label(row: Dict) -> str:
    """Return the ``"YYYY Tn"`` period label of one Registradores CSV row.

    Pure function; mirrors the shape :func:`update_market_data.latest_ine_period`
    already produces for INE so ``opposition_tierra.parse_data_date`` (which
    accepts ``"2026 T2"``) needs no change for the new source. Returns ``""``
    when ``ano``/``trim`` are missing rather than guessing.
    """
    if not isinstance(row, dict):
        return ""
    year, quarter = row.get("ano"), row.get("trim")
    if year is None or quarter is None:
        return ""
    return f"{year} T{quarter}"


def _normalize(text: str) -> str:
    """Lower-case and strip accents so INE labels can be matched robustly."""
    import unicodedata
    stripped = unicodedata.normalize("NFKD", text or "")
    return "".join(ch for ch in stripped if not unicodedata.combining(ch)).lower()


# ═══════════════════════════════════════════════════════════
# TEXT CATALOGUE (ca / es / en) — every user-facing string lives here
# ═══════════════════════════════════════════════════════════

SUPPORTED_LANGUAGES = ("ca", "es", "en")

TEXT = {
    "ca": {
        "report_title": "RAILNEXUS VALUE — INTEL·LIGÈNCIA DE MERCAT",
        "address": "Adreça", "municipality": "Municipi", "cadastral_ref": "Ref. catastral",
        "date": "Data", "section_land": "1. CLASSIFICACIÓ DE SÒL", "class": "Classe",
        "designation": "Qualificació", "construction_allowed": "Permet construcció",
        "yes": "✅ SÍ", "no": "❌ NO", "current_plan": "Pla vigent", "siu_map": "🗺️ Mapa SIU",
        "unverified": "⚠️ NO VERIFICAT PER A AQUESTA PARCEL·LA",
        "zoning_source": "Font de la classificació",
        "reason_zoning_unverified": "Classificació del sòl no verificada per a aquesta parcel·la "
                                    "(cap consulta SIU/MUC amb resultat per al punt).",
        "action_zoning_unverified": "Comprovar la qualificació al visor SIU / MUC abans de concloure.",
        "section_prices": "2. PREUS DE MERCAT", "source": "Font", "radius": "Radi",
        "data_status": "Estat de dades", "data_date": "Data del dada",
        "no_live_prices": "Sense preus web vius; no es mostren valors substitutius.",
        "source_error": "Error de font", "new_build": "Obra nova", "resale": "Segona mà",
        "listings": "anuncis", "area_avg": "Promig zona", "premium": "Prima nova vs segona",
        "historical_warning": "⚠ VALORS HISTÒRICS ({date}) — context, NO mercat actual.",
        "section_projections": "3. PROJECCIONS", "trend": "Tendència", "annual": "anual",
        "new_6m": "Nova a 6 mesos", "new_12m": "Nova a 12 mesos", "resale_6m": "Segona a 6 mesos",
        "confidence": "Confiança", "method": "Mètode",
        "no_projections": "No calculades: falta una base de preus web viva.",
        "no_trend": "No calculades: l'INE no ha retornat una sèrie de variació utilitzable.",
        "section_feasibility": "4. VIABILITAT DE DESENVOLUPAMENT",
        "estimated_costs": "Costos estimats", "construction": "Construcció", "land": "Sòl",
        "soft_costs": "Tous/financers", "total": "TOTAL", "margins": "Marges",
        "gross_now": "Brut actual", "projected_6m": "Projectat 6m", "risks": "Riscos",
        "reason": "Motiu", "action": "Acció",
        "footer_1": "⚠ Les projeccions es basen en tendències passades.",
        "footer_2": "No constitueixen assessorament d'inversió.", "sources": "Fonts",
        "generated_by": "Generat per RailNexus Value",
        # trend / confidence / method
        "trend_up": "ALCISTA", "trend_flat": "ESTABLE", "trend_down": "BAIXISTA",
        "conf_high": "alta", "conf_medium": "mitjana", "conf_low": "baixa", "conf_none": "sense dades",
        "method_ine_weighted_regression": "Regressió lineal ponderada sobre dades trimestrals INE",
        "method_compound_trend": "Projecció composta basada en tendència anual",
        "method_historical_reference_trend": "Tendència de referència històrica (no actual)",
        "method_no_trend_data": "Sense dades de tendència",
        "src_ine": "INE IPV", "src_reference": "Dades de referència", "src_catastro": "Catastro", "src_siu": "SIU",
        # feasibility
        "sem_green": "🟢 VERD", "sem_yellow": "🟡 GROC", "sem_red": "🔴 VERMELL", "sem_none": "⚪ NO VERIFICAT",
        "viable_unverified": "NO CONCLOENT",
        "reason_no_live": "No hi ha preus de mercat descarregats en viu.",
        "action_no_live": "Executar update_market_data.py i repetir l'anàlisi.",
        "viable_no_build": "NO VIABLE", "reason_no_build": "Sòl sense permís de construcció",
        "action_no_build": "No procedeix anàlisi de mercat",
        "viable_green": "VIABLE — Marge atractiu",
        "viable_yellow": "VIABLE AMB CONDICIONS — Marge ajustat",
        "viable_marginal": "MARGINAL — Requereix optimització de costos",
        "viable_red": "NO VIABLE — Costos superiors al preu de venda",
        "risk_market": "MERCAT", "risk_competition": "COMPETÈNCIA",
        "risk_overheating": "Creixement del {pct}% anual pot indicar sobreescalfament",
        "risk_falling": "Preus a la baixa ({pct}%) — risc de pèrdues",
        "risk_premium": "Prima d'obra nova del {pct}% sobre segona mà — pot limitar demanda",
        "risk_zoning": "URBANISME",
        "risk_zoning_use_unverified": "Classe de sòl verificada al punt (SIU) però la qualificació "
                                      "(ús: residencial / industrial / zona verda) NO — comprovar el pla municipal",
        "risk_zoning_development": "Sòl que exigeix planejament/urbanització prèvia: {note}",
        "risk_zoning_residential_unknown": "La qualificació no determina si s'hi admet habitatge ({calificacion})",
        "cost_note": "Costos de referència CSCAE 2025. No inclou financers.",
    },
    "es": {
        "report_title": "RAILNEXUS VALUE — INTELIGENCIA DE MERCADO",
        "address": "Dirección", "municipality": "Municipio", "cadastral_ref": "Ref. catastral",
        "date": "Fecha", "section_land": "1. CLASIFICACIÓN DEL SUELO", "class": "Clase",
        "designation": "Calificación", "construction_allowed": "Permite construcción",
        "yes": "✅ SÍ", "no": "❌ NO", "current_plan": "Plan vigente", "siu_map": "🗺️ Mapa SIU",
        "unverified": "⚠️ NO VERIFICADO PARA ESTA PARCELA",
        "zoning_source": "Fuente de la clasificación",
        "reason_zoning_unverified": "Clasificación del suelo no verificada para esta parcela "
                                    "(ninguna consulta SIU/MUC con resultado para el punto).",
        "action_zoning_unverified": "Comprobar la calificación en el visor SIU / MUC antes de concluir.",
        "section_prices": "2. PRECIOS DE MERCADO", "source": "Fuente", "radius": "Radio",
        "data_status": "Estado de datos", "data_date": "Fecha del dato",
        "no_live_prices": "Sin precios web vivos; no se muestran valores sustitutivos.",
        "source_error": "Error de fuente", "new_build": "Obra nueva", "resale": "Segunda mano",
        "listings": "anuncios", "area_avg": "Promedio zona", "premium": "Prima nueva vs segunda",
        "historical_warning": "⚠ VALORES HISTÓRICOS ({date}) — contexto, NO mercado actual.",
        "section_projections": "3. PROYECCIONES", "trend": "Tendencia", "annual": "anual",
        "new_6m": "Nueva a 6 meses", "new_12m": "Nueva a 12 meses", "resale_6m": "Segunda a 6 meses",
        "confidence": "Confianza", "method": "Método",
        "no_projections": "No calculadas: falta una base de precios web viva.",
        "no_trend": "No calculadas: el INE no ha devuelto una serie de variación utilizable.",
        "section_feasibility": "4. VIABILIDAD DE DESARROLLO",
        "estimated_costs": "Costes estimados", "construction": "Construcción", "land": "Suelo",
        "soft_costs": "Indirectos/financieros", "total": "TOTAL", "margins": "Márgenes",
        "gross_now": "Bruto actual", "projected_6m": "Proyectado 6m", "risks": "Riesgos",
        "reason": "Motivo", "action": "Acción",
        "footer_1": "⚠ Las proyecciones se basan en tendencias pasadas.",
        "footer_2": "No constituyen asesoramiento de inversión.", "sources": "Fuentes",
        "generated_by": "Generado por RailNexus Value",
        "trend_up": "ALCISTA", "trend_flat": "ESTABLE", "trend_down": "BAJISTA",
        "conf_high": "alta", "conf_medium": "media", "conf_low": "baja", "conf_none": "sin datos",
        "method_ine_weighted_regression": "Regresión lineal ponderada sobre datos trimestrales INE",
        "method_compound_trend": "Proyección compuesta basada en tendencia anual",
        "method_historical_reference_trend": "Tendencia de referencia histórica (no actual)",
        "method_no_trend_data": "Sin datos de tendencia",
        "src_ine": "INE IPV", "src_reference": "Datos de referencia", "src_catastro": "Catastro", "src_siu": "SIU",
        "sem_green": "🟢 VERDE", "sem_yellow": "🟡 AMARILLO", "sem_red": "🔴 ROJO", "sem_none": "⚪ NO VERIFICADO",
        "viable_unverified": "NO CONCLUYENTE",
        "reason_no_live": "No hay precios de mercado descargados en vivo.",
        "action_no_live": "Ejecutar update_market_data.py y repetir el análisis.",
        "viable_no_build": "NO VIABLE", "reason_no_build": "Suelo sin permiso de construcción",
        "action_no_build": "No procede análisis de mercado",
        "viable_green": "VIABLE — Margen atractivo",
        "viable_yellow": "VIABLE CON CONDICIONES — Margen ajustado",
        "viable_marginal": "MARGINAL — Requiere optimización de costes",
        "viable_red": "NO VIABLE — Costes superiores al precio de venta",
        "risk_market": "MERCADO", "risk_competition": "COMPETENCIA",
        "risk_overheating": "Crecimiento del {pct}% anual puede indicar sobrecalentamiento",
        "risk_falling": "Precios a la baja ({pct}%) — riesgo de pérdidas",
        "risk_premium": "Prima de obra nueva del {pct}% sobre segunda mano — puede limitar la demanda",
        "risk_zoning": "URBANISMO",
        "risk_zoning_use_unverified": "Clase de suelo verificada en el punto (SIU) pero la calificación "
                                      "(uso: residencial / industrial / zona verde) NO — comprobar el plan municipal",
        "risk_zoning_development": "Suelo que exige planeamiento/urbanización previa: {note}",
        "risk_zoning_residential_unknown": "La calificación no determina si admite vivienda ({calificacion})",
        "cost_note": "Costes de referencia CSCAE 2025. No incluye financieros.",
    },
    "en": {
        "report_title": "RAILNEXUS VALUE — MARKET INTELLIGENCE",
        "address": "Address", "municipality": "Municipality", "cadastral_ref": "Cadastral ref.",
        "date": "Date", "section_land": "1. LAND CLASSIFICATION", "class": "Class",
        "designation": "Designation", "construction_allowed": "Construction allowed",
        "yes": "✅ YES", "no": "❌ NO", "current_plan": "Current plan", "siu_map": "🗺️ SIU map",
        "unverified": "⚠️ NOT VERIFIED FOR THIS PARCEL",
        "zoning_source": "Zoning source",
        "reason_zoning_unverified": "Land classification not verified for this parcel "
                                    "(no SIU/MUC lookup returned a result for the point).",
        "action_zoning_unverified": "Check the designation in the SIU / MUC viewer before concluding.",
        "section_prices": "2. MARKET PRICES", "source": "Source", "radius": "Radius",
        "data_status": "Data status", "data_date": "Data date",
        "no_live_prices": "No live web prices; no substitute values are shown.",
        "source_error": "Source error", "new_build": "New build", "resale": "Resale",
        "listings": "listings", "area_avg": "Area average", "premium": "New-build premium",
        "historical_warning": "⚠ HISTORICAL VALUES ({date}) — context only, NOT the current market.",
        "section_projections": "3. PROJECTIONS", "trend": "Trend", "annual": "annual",
        "new_6m": "New build at 6 months", "new_12m": "New build at 12 months",
        "resale_6m": "Resale at 6 months", "confidence": "Confidence", "method": "Method",
        "no_projections": "Not calculated: a live web price basis is missing.",
        "no_trend": "Not calculated: INE did not return a usable variation series.",
        "section_feasibility": "4. DEVELOPMENT FEASIBILITY",
        "estimated_costs": "Estimated costs", "construction": "Construction", "land": "Land",
        "soft_costs": "Soft/finance", "total": "TOTAL", "margins": "Margins",
        "gross_now": "Current gross", "projected_6m": "Projected 6m", "risks": "Risks",
        "reason": "Reason", "action": "Action",
        "footer_1": "⚠ Projections are based on past trends.",
        "footer_2": "This is not investment advice.", "sources": "Sources",
        "generated_by": "Generated by RailNexus Value",
        "trend_up": "RISING", "trend_flat": "STABLE", "trend_down": "FALLING",
        "conf_high": "high", "conf_medium": "medium", "conf_low": "low", "conf_none": "no data",
        "method_ine_weighted_regression": "Weighted linear regression on INE quarterly data",
        "method_compound_trend": "Compound projection from annual trend",
        "method_historical_reference_trend": "Historical reference trend (not current)",
        "method_no_trend_data": "No trend data",
        "src_ine": "INE HPI", "src_reference": "Reference data", "src_catastro": "Catastro", "src_siu": "SIU",
        "sem_green": "🟢 GREEN", "sem_yellow": "🟡 YELLOW", "sem_red": "🔴 RED", "sem_none": "⚪ NOT VERIFIED",
        "viable_unverified": "INCONCLUSIVE",
        "reason_no_live": "No live market prices were downloaded.",
        "action_no_live": "Run update_market_data.py and repeat the analysis.",
        "viable_no_build": "NOT VIABLE", "reason_no_build": "Land without construction permission",
        "action_no_build": "Market analysis not applicable",
        "viable_green": "VIABLE — Attractive margin",
        "viable_yellow": "VIABLE WITH CONDITIONS — Tight margin",
        "viable_marginal": "MARGINAL — Requires cost optimisation",
        "viable_red": "NOT VIABLE — Costs exceed sale price",
        "risk_market": "MARKET", "risk_competition": "COMPETITION",
        "risk_overheating": "Annual growth of {pct}% may indicate overheating",
        "risk_falling": "Falling prices ({pct}%) — loss risk",
        "risk_premium": "New-build premium of {pct}% over resale — may limit demand",
        "risk_zoning": "ZONING",
        "risk_zoning_use_unverified": "Land class verified at the point (SIU) but the designation "
                                      "(use: residential / industrial / green) is NOT — check the municipal plan",
        "risk_zoning_development": "Land that requires prior planning/urbanisation: {note}",
        "risk_zoning_residential_unknown": "The designation does not settle whether housing is allowed ({calificacion})",
        "cost_note": "CSCAE 2025 reference costs. Finance costs not included.",
    },
}


def tr(language: str, key: str, **fmt) -> str:
    """Translate ``key`` into ``language`` (falls back to Catalan, the historical default)."""
    catalogue = TEXT.get(language) or TEXT["ca"]
    template = catalogue.get(key) or TEXT["ca"].get(key) or key
    return template.format(**fmt) if fmt else template


# ═══════════════════════════════════════════════════════════
# DATA MODELS
# ═══════════════════════════════════════════════════════════

@dataclass
class ParcelData:
    """Data from Catastro for a specific parcel."""
    ref_catastral: str = ""
    direccion: str = ""
    municipio: str = ""
    provincia: str = ""
    superficie_suelo_m2: float = 0
    superficie_construida_m2: float = 0
    año_construccion: int = 0
    uso_principal: str = ""
    num_plantas: int = 0
    coordinates: Tuple[float, float] = (0, 0)  # lat, lon
    raw_response: str = ""
    uso: str = ""

@dataclass
class LandClassification:
    """Urban planning classification for a location.

    v19 contract (P0 fix): ``permite_construccion`` / ``permite_residencial``
    are ``True`` / ``False`` ONLY when something actually checked the parcel
    (``verified_for_parcel=True``: a SIU WMS GetFeatureInfo hit, a MUC
    parcel record, ...). Otherwise they are ``None`` = "not verified for this
    parcel" and ``__post_init__`` enforces it — a record cannot be built with
    ``permite_construccion=True`` and ``verified_for_parcel=False``. v16–v18
    returned a fixed ``True / residencial / Alta`` for ANY point inside
    Madrid, Barcelona, Valencia, Sevilla or Málaga from city-wide hectare
    totals, i.e. fabricated per-parcel data; that path is gone.
    """
    clase_suelo: str = ""  # urbano, urbanizable, no_urbanizable ("" = unknown)
    calificacion: str = ""  # residencial, industrial, etc. ("" = unknown)
    permite_construccion: Optional[bool] = None   # None = NOT verified for this parcel
    permite_residencial: Optional[bool] = None    # None = NOT verified for this parcel
    densidad: str = ""
    plan_vigente: str = ""  # PGOU/POUM name
    observaciones: str = ""
    source: str = "SIU"
    verified_for_parcel: bool = False              # True only after a real per-parcel lookup
    verification_status: str = "UNVERIFIED"        # VERIFIED_PARCEL | UNVERIFIED | UNKNOWN | ERROR
    raw: Dict = field(default_factory=dict)        # per-parcel attributes as returned by the service

    def __post_init__(self):
        if not self.verified_for_parcel:
            # Invariant: unverified records never carry a buildability verdict.
            self.permite_construccion = None
            self.permite_residencial = None
            if self.verification_status == "VERIFIED_PARCEL":
                self.verification_status = "UNVERIFIED"
        elif self.verification_status in ("", "UNVERIFIED"):
            self.verification_status = "VERIFIED_PARCEL"


@dataclass
class MarketPrice:
    """Market price data for a zone."""
    precio_m2_nueva: float = 0
    precio_m2_segunda: float = 0
    precio_m2_promedio: float = 0
    num_listings_nueva: int = 0
    num_listings_segunda: int = 0
    tamaño_medio_nueva_m2: float = 0
    tamaño_medio_segunda_m2: float = 0
    ratio_nueva_vs_segunda: float = 0  # e.g. 1.24 = nueva is 24% more
    precio_mediana_nueva: float = 0
    precio_mediana_segunda: float = 0
    radio_busqueda_m: int = 0
    fecha_datos: str = ""
    source: str = ""
    data_status: str = "NO_LIVE_MARKET_DATA"
    source_errors: List[str] = field(default_factory=list)


@dataclass
class PriceTrend:
    """Historical price trend and projection."""
    variacion_trimestral: List[float] = field(default_factory=list)
    variacion_anual_pct: float = 0
    variacion_2_años_pct: float = 0
    tendencia: str = ""  # "alcista", "estable", "bajista"
    proyeccion_6_meses_nueva: float = 0
    proyeccion_6_meses_segunda: float = 0
    proyeccion_12_meses_nueva: float = 0
    confianza: str = ""  # "alta", "media", "baja"
    metodo: str = ""
    fuentes: List[str] = field(default_factory=list)


@dataclass
class MarketReport:
    """Complete market intelligence report."""
    parcel: ParcelData
    land_class: LandClassification
    market: MarketPrice
    trend: PriceTrend
    feasibility: Dict = field(default_factory=dict)
    semaforo: str = ""
    recomendacion: str = ""
    timestamp: str = ""


# ═══════════════════════════════════════════════════════════
# 1. CATASTRO MODULE
# ═══════════════════════════════════════════════════════════

class Catastro:
    """
    Spanish Catastro public API.
    Documentation: https://www.catastro.meh.es/documentos/09102014_Eng.pdf
    """

    BASE = "https://ovc.catastro.meh.es/ovcservweb"

    @staticmethod
    def by_coordinates(lat: float, lon: float) -> ParcelData:
        """Get parcel data from GPS coordinates."""
        url = (f"{Catastro.BASE}/OVCSWLocalizacionRC/"
               f"OVCCoordenadas.asmx/Consulta_RCCOOR"
               f"?SRS=EPSG:4326&Coordenada_X={lon}&Coordenada_Y={lat}")
        try:
            resp = requests.get(url, timeout=10)
            if resp.status_code != 200:
                return ParcelData(raw_response=f"HTTP {resp.status_code}")

            root = ET.fromstring(resp.text)
            parcel = ParcelData(coordinates=(lat, lon), raw_response=resp.text[:500])

            # Parse XML — namespace varies
            for elem in root.iter():
                tag = elem.tag.split("}")[-1] if "}" in elem.tag else elem.tag
                tag_lower = tag.lower()

                if tag_lower == "pc1" and elem.text:
                    parcel.ref_catastral = elem.text
                elif tag_lower == "pc2" and elem.text:
                    parcel.ref_catastral += elem.text
                elif tag_lower == "ldt" and elem.text:
                    parcel.direccion = elem.text
                elif tag_lower == "cm" and elem.text:
                    parcel.municipio = elem.text
                elif tag_lower == "cp" and elem.text:
                    parcel.provincia = elem.text

            return parcel

        except Exception as e:
            return ParcelData(raw_response=f"Error: {e}")

    @staticmethod
    def by_address(provincia: str, municipio: str,
                   via: str, numero: str) -> ParcelData:
        """Get parcel data from street address."""
        url = (f"{Catastro.BASE}/OVCSWLocalizacionRC/"
               f"OVCCallejero.asmx/ObtenerCallejero"
               f"?Provincia={provincia}&Municipio={municipio}"
               f"&TipoVia=&NombreVia={via}&Numero={numero}")
        try:
            resp = requests.get(url, timeout=10)
            if resp.status_code != 200:
                return ParcelData(raw_response=f"HTTP {resp.status_code}")

            parcel = ParcelData(
                provincia=provincia,
                municipio=municipio,
                direccion=f"{via} {numero}, {municipio}",
                raw_response=resp.text[:500]
            )

            # Parse XML for ref catastral
            root = ET.fromstring(resp.text)
            for elem in root.iter():
                tag = elem.tag.split("}")[-1] if "}" in elem.tag else elem.tag
                if tag.lower() in ("rc", "pc1", "pc2") and elem.text:
                    parcel.ref_catastral += elem.text

            return parcel

        except Exception as e:
            return ParcelData(raw_response=f"Error: {e}")

    @staticmethod
    def get_full_data(ref_catastral: str) -> Dict:
        """
        Get full parcel details from referencia catastral.
        Uses INSPIRE ATOM service for detailed data.
        """
        # INSPIRE Cadastral Parcels service
        url = (f"https://ovc.catastro.meh.es/ovcservweb/"
               f"OVCSWLocalizacionRC/OVCCallejeroCodigos.asmx/"
               f"Consulta_DNPRC?RC={ref_catastral}")
        try:
            resp = requests.get(url, timeout=10)
            return {"status": "ok", "content": resp.text[:2000]}
        except Exception as e:
            return {"status": "error", "message": str(e)}


# ═══════════════════════════════════════════════════════════
# 2. SIU / LAND CLASSIFICATION MODULE
# ═══════════════════════════════════════════════════════════

class SIUArcGISClient:
    """ArcGIS REST ``identify`` client for the SIU map services (v19).

    ``identify(service, lat, lon)`` returns ``{"status": "ok", "results":
    [{"layerName", "attributes"}...]}`` — an empty list means the point is
    outside every polygon of the service (e.g. outside Spain) — or
    ``{"status": "error", "message"}``. No fallback, no guessing.
    """

    HEADERS = {"User-Agent": f"RailNexus-MarketIntel/{AGENT_VERSION} (+https://value.railnexus.io)"}

    @classmethod
    def identify(cls, service_url: str, lat: float, lon: float, timeout: int = 30) -> Dict:
        delta = 0.002
        params = {
            "f": "json", "geometry": f"{lon},{lat}", "geometryType": "esriGeometryPoint",
            "sr": 4326, "layers": "all", "tolerance": 0, "returnGeometry": "false",
            "mapExtent": f"{lon-delta},{lat-delta},{lon+delta},{lat+delta}",
            "imageDisplay": "400,400,96",
        }
        url = service_url.rstrip("/") + "/identify"
        try:
            resp = requests.get(url, params=params, headers=cls.HEADERS, timeout=timeout)
        except Exception as e:
            return {"status": "error", "message": f"{type(e).__name__}: {e}", "url": url}
        if resp.status_code != 200:
            return {"status": "error", "message": f"HTTP {resp.status_code}", "url": url}
        try:
            payload = resp.json()
        except ValueError:
            return {"status": "error", "message": "non-JSON body", "url": url}
        if not isinstance(payload, dict) or "results" not in payload:
            err = payload.get("error", {}) if isinstance(payload, dict) else {}
            return {"status": "error", "url": url,
                    "message": f"ArcGIS error {err.get('code', '')}: {err.get('message', 'no results key')}".strip()}
        results = [{"layerName": r.get("layerName", ""), "attributes": r.get("attributes") or {}}
                   for r in payload["results"] if isinstance(r, dict)]
        return {"status": "ok", "results": results, "url": url}


class MUCWMSClient:
    """WMS 1.1.1 GetFeatureInfo client for the Mapa urbanístic de Catalunya (v19).

    ``get_feature_info(layer, lat, lon)`` returns ``{"status": "ok",
    "features": [properties...]}`` (empty = no polygon under the point, i.e.
    outside Catalonia or a gap in the MUC) or ``{"status": "error", "message"}``.
    The query box is ±``half_m`` metres around the point in EPSG:3857 with the
    pixel of interest at its centre.
    """

    HEADERS = SIUArcGISClient.HEADERS

    @classmethod
    def get_feature_info(cls, layer: str, lat: float, lon: float, half_m: float = 50.0,
                         timeout: int = 30) -> Dict:
        x, y = web_mercator(lat, lon)
        px = 101
        params = {
            "SERVICE": "WMS", "VERSION": "1.1.1", "REQUEST": "GetFeatureInfo",
            "LAYERS": layer, "QUERY_LAYERS": layer, "STYLES": "",
            "SRS": "EPSG:3857", "BBOX": f"{x-half_m},{y-half_m},{x+half_m},{y+half_m}",
            "WIDTH": px, "HEIGHT": px, "X": px // 2, "Y": px // 2,
            "INFO_FORMAT": "application/json", "FEATURE_COUNT": 5,
        }
        try:
            resp = requests.get(MUC_WMS_URL, params=params, headers=cls.HEADERS, timeout=timeout)
        except Exception as e:
            return {"status": "error", "message": f"{type(e).__name__}: {e}", "layer": layer}
        if resp.status_code != 200:
            return {"status": "error", "message": f"HTTP {resp.status_code}", "layer": layer}
        try:
            payload = resp.json()
        except ValueError:
            return {"status": "error", "message": "non-JSON body (ServiceException?)", "layer": layer}
        feats = payload.get("features") if isinstance(payload, dict) else None
        if not isinstance(feats, list):
            return {"status": "error", "message": "no FeatureCollection in body", "layer": layer}
        return {"status": "ok", "layer": layer,
                "features": [f.get("properties") or {} for f in feats if isinstance(f, dict)]}

    @staticmethod
    def in_coverage(lat: float, lon: float) -> bool:
        min_lon, min_lat, max_lon, max_lat = MUC_BBOX_WGS84
        return min_lon <= lon <= max_lon and min_lat <= lat <= max_lat


class SIUClassifier:
    """Land classification at a point (v19: real per-point lookups).

    ``classify(lat, lon, municipio)`` runs :meth:`lookup_parcel`:
    1. inside the MUC bounding box (Catalonia): WMS GetFeatureInfo on the MUC
       classification + qualification layers -> parcel-level class AND use
       (``verification_level = "muc_qualificacio"``);
    2. otherwise (or when the MUC has no polygon there): ArcGIS ``identify`` on
       the SIU CLASES_DE_SUELO service -> the land class of the polygon under
       the point (``"siu_clase_suelo"``; the use is NOT known, said explicitly);
       ``Planeamiento_Vigente`` adds the plan in force for the municipality;
    3. nothing answered / point outside coverage / services down -> the
       UNVERIFIED record (``permite_construccion`` None, city-wide reference
       figures only, errors listed) — never the pre-v19 fabricated verdict.
    """

    # Catastro use codes → land classification mapping
    USE_CLASSIFICATION = {
        "A": ("Almacén/Estacionamiento", False),
        "V": ("Residencial", True),
        "I": ("Industrial", False),
        "O": ("Oficinas", True),
        "C": ("Comercial", True),
        "K": ("Deportivo", False),
        "T": ("Espectáculos", False),
        "G": ("Ocio/Hostelería", True),
        "Y": ("Sanidad/Beneficencia", False),
        "E": ("Cultural", False),
        "R": ("Religioso", False),
        "M": ("Obras urbanización", False),
        "P": ("Edificio singular", False),
        "B": ("Almacén agrario", False),
        "J": ("Industrial agrario", False),
        "Z": ("Agrario", False),
    }

    # Reference data for major cities (from SIU visor). v19: these are
    # CITY-WIDE hectare totals; they never produce a per-parcel verdict.
    CITY_LAND_DATA = {
        "valencia": {
            "suelo_urbano_ha": 4523.12,
            "urbanizable_delimitado_ha": 760.94,
            "urbanizable_no_delimitado_ha": 312.45,
            "no_urbanizable_ha": 8234.67,
            "plan_vigente": "PGOU Valencia (Rev. 2022)",
        },
        "barcelona": {
            "suelo_urbano_ha": 7412.30,
            "urbanizable_delimitado_ha": 245.80,
            "urbanizable_no_delimitado_ha": 0,
            "no_urbanizable_ha": 2456.90,
            "plan_vigente": "PGM Barcelona (1976, con modificaciones)",
        },
        "madrid": {
            "suelo_urbano_ha": 24532.00,
            "urbanizable_delimitado_ha": 4120.50,
            "urbanizable_no_delimitado_ha": 1835.20,
            "no_urbanizable_ha": 30124.30,
            "plan_vigente": "PGOU Madrid (1997, revisión 2025)",
        },
        "sevilla": {
            "suelo_urbano_ha": 6234.40,
            "urbanizable_delimitado_ha": 1456.30,
            "urbanizable_no_delimitado_ha": 523.10,
            "no_urbanizable_ha": 5867.20,
            "plan_vigente": "PGOU Sevilla (2006)",
        },
        "malaga": {
            "suelo_urbano_ha": 3245.60,
            "urbanizable_delimitado_ha": 987.40,
            "urbanizable_no_delimitado_ha": 234.50,
            "no_urbanizable_ha": 35467.50,
            "plan_vigente": "PGOU Málaga (2011)",
        },
    }

    @classmethod
    def plan_vigente_siu(cls, lat: float, lon: float, errors: Optional[List[str]] = None) -> Dict:
        """Municipality plan in force from SIU ``Planeamiento_Vigente`` (``{}`` if none)."""
        res = SIUArcGISClient.identify(SIU_PLANEAMIENTO_MAPSERVER, lat, lon)
        if res["status"] != "ok":
            if errors is not None:
                errors.append(f"SIU Planeamiento_Vigente: {res['message']}")
            return {}
        for r in res["results"]:
            a = r["attributes"]
            if a.get("FiguraVigente"):
                return {"figura": str(a.get("FiguraVigente", "")).strip(),
                        "fecha": str(a.get("FechaFigura", "")).strip(),
                        "municipio": str(a.get("nombre") or a.get("NAMEUNIT") or "").strip(),
                        "cod_ine": str(a.get("CodINE", "")).strip(),
                        "url": str(a.get("UrlLink", "")).strip(),
                        "observaciones": str(a.get("observaciones", "")).strip()}
        return {}

    @classmethod
    def lookup_muc(cls, lat: float, lon: float, errors: Optional[List[str]] = None) -> Optional[LandClassification]:
        """Parcel-level class + use from the MUC WMS; ``None`` when no polygon there."""
        clas = MUCWMSClient.get_feature_info(MUC_LAYER_CLASSIFICATION, lat, lon)
        qual = MUCWMSClient.get_feature_info(MUC_LAYER_QUALIFICATION, lat, lon)
        for res, name in ((clas, "CLAS"), (qual, "QUAL")):
            if res["status"] != "ok" and errors is not None:
                errors.append(f"MUC {name}: {res['message']}")
        c = (clas.get("features") or [None])[0] if clas["status"] == "ok" else None
        q = (qual.get("features") or [None])[0] if qual["status"] == "ok" else None
        if not c and not q:
            return None
        c, q = c or {}, q or {}
        code_clas = str(c.get("CODI_CLAS_MUC", "")).strip().upper()
        code_qual = str(q.get("CODI_QUAL_MUC", "")).strip().upper()
        permite, residencial, calificacion = muc_qualification_verdict(code_qual)
        if not code_qual and code_clas == "SNU":
            permite, residencial, calificacion = False, False, "no urbanizable"
        desc_qual = " / ".join(x for x in (str(q.get("DESC_QUAL_MUC", "")).strip(),
                                            str(q.get("DESC_QUAL_AJUNT", "")).strip()) if x)
        desc_clas = " / ".join(x for x in (str(c.get("DESC_CLAS_MUC", "")).strip(),
                                            str(c.get("DESC_CLAS_AJUNT", "")).strip()) if x)
        obs = [f"MUC classificació: {code_clas} {desc_clas}".strip(),
               f"MUC qualificació: {code_qual} {desc_qual}".strip()]
        if permite is None and code_qual:
            obs.append("codi de qualificació fora de la taula R/A/M/S/N: veredicte no decidit")
        return LandClassification(
            clase_suelo=MUC_CLASS_KEYS.get(code_clas, _normalize(code_clas)),
            calificacion=(f"{calificacion}: {desc_qual}" if calificacion and desc_qual else calificacion or desc_qual),
            permite_construccion=permite, permite_residencial=residencial,
            observaciones=" | ".join(obs),
            source=MUC_VERIFIED_SOURCE,
            verified_for_parcel=True,
            verification_status="VERIFIED_PARCEL",
            raw={"verification_level": "muc_qualificacio", "clas": c, "qual": q,
                 "codi_ine": str(q.get("CODI_INE") or c.get("CODI_INE") or "")},
        )

    @classmethod
    def lookup_siu(cls, lat: float, lon: float, errors: Optional[List[str]] = None) -> Optional[LandClassification]:
        """Land class of the SIU polygon under the point; ``None`` when there is none."""
        res = SIUArcGISClient.identify(SIU_CLASES_SUELO_MAPSERVER, lat, lon)
        if res["status"] != "ok":
            if errors is not None:
                errors.append(f"SIU CLASES_DE_SUELO: {res['message']}")
            return None
        hit = next((r["attributes"] for r in res["results"] if r["attributes"].get("ClaseSuelo")), None)
        if not hit:
            return None
        clase = str(hit["ClaseSuelo"]).strip()
        permite, key, note = siu_clase_suelo_verdict(clase)
        obs = [f"SIU clase de suelo en el punto: {clase}"]
        if note:
            obs.append(note)
        obs.append("calificación (uso: residencial/industrial/zona verde...) NO disponible en el SIU "
                   "nacional — comprobar en el planeamiento municipal")
        if permite is None:
            obs.append("valor de ClaseSuelo fuera de la tabla conocida: veredicto no decidido")
        return LandClassification(
            clase_suelo=key, calificacion="",
            permite_construccion=permite, permite_residencial=None,
            observaciones=" | ".join(obs),
            source=SIU_VERIFIED_SOURCE,
            verified_for_parcel=True,
            verification_status="VERIFIED_PARCEL",
            raw={"verification_level": "siu_clase_suelo", "clase_suelo": clase,
                 "prov_ine": str(hit.get("ProvINE", "")), "nucl_rural": str(hit.get("NuclRural", ""))},
        )

    @classmethod
    def lookup_parcel(cls, lat: float, lon: float, municipio: str = "",
                      errors: Optional[List[str]] = None) -> Optional[LandClassification]:
        """Real per-point lookup: MUC (Catalonia) first, then SIU; ``None`` if neither answers."""
        land = None
        if MUCWMSClient.in_coverage(lat, lon):
            land = cls.lookup_muc(lat, lon, errors)
        if land is None:
            land = cls.lookup_siu(lat, lon, errors)
        if land is None:
            return None
        plan = cls.plan_vigente_siu(lat, lon, errors)
        if plan:
            land.plan_vigente = f"{plan['figura']} ({plan['fecha']})".strip() if plan["fecha"] else plan["figura"]
            land.raw["plan_vigente"] = plan
            if plan.get("cod_ine"):
                land.raw.setdefault("codi_ine", plan["cod_ine"])
        return land

    @classmethod
    def classify(cls, lat: float, lon: float,
                 municipio: str = "") -> LandClassification:
        """Classify land at the coordinates (v19: real lookup, honest fallback).

        Returns a ``verified_for_parcel=True`` record only when the MUC or the
        SIU answered for THIS point; otherwise the UNVERIFIED record whose
        ``permite_*`` are ``None`` and whose observations list what was tried.
        """
        errors: List[str] = []
        land = cls.lookup_parcel(lat, lon, municipio, errors)
        if land is not None:
            if errors:
                land.raw["lookup_errors"] = errors
            return land

        muni_lower = _normalize(municipio).strip()   # v19: accent-insensitive ("Málaga")

        # Check if we have reference data
        city_data = None
        for city_key, data in cls.CITY_LAND_DATA.items():
            if city_key in muni_lower:
                city_data = data
                break

        tried = ("consulta por punto sin resultado: " + "; ".join(errors)) if errors else (
            "consulta por punto sin resultado (fuera de cobertura SIU/MUC o servicio sin polígono aquí)")
        if city_data:
            # v19 P0: a city match is NOT a parcel check. The hectare totals
            # are city-wide aggregates and say nothing about THIS point (a
            # park, an industrial plot and protected land all match "madrid").
            # No clase_suelo / calificacion / densidad / permite_* is asserted.
            return LandClassification(
                plan_vigente=city_data["plan_vigente"],
                observaciones=(
                    "SIN VERIFICAR PARA ESTA PARCELA — dato agregado del municipio, no del punto: "
                    f"suelo urbano {city_data['suelo_urbano_ha']:,.0f} ha | "
                    f"urbanizable {city_data['urbanizable_delimitado_ha']:,.0f} ha | "
                    f"no urbanizable {city_data['no_urbanizable_ha']:,.0f} ha. "
                    f"{tried}. Consultar SIU: https://mapas.fomento.gob.es/VisorSIU/"
                ),
                source=SIU_UNVERIFIED_SOURCE,
                verified_for_parcel=False,
                verification_status="ERROR" if errors else "UNVERIFIED",
                raw={"lookup_errors": errors},
            )

        return LandClassification(
            observaciones="No hay datos de referencia para este municipio ni consulta por parcela con "
                         f"resultado. {tried}. Consultar SIU: https://mapas.fomento.gob.es/VisorSIU/",
            source="SIU (sin datos)",
            verified_for_parcel=False,
            verification_status="ERROR" if errors else "UNKNOWN",
            raw={"lookup_errors": errors},
        )

    @classmethod
    def get_wms_url(cls, lat: float, lon: float,
                    width: int = 800, height: int = 600) -> str:
        """
        Generate a direct URL to the SIU WMS viewer centered on coordinates.
        User can click this to see the official map.
        """
        # EPSG:4326 bbox: minlon, minlat, maxlon, maxlat
        delta = 0.01  # ~1km radius
        bbox = f"{lon-delta},{lat-delta},{lon+delta},{lat+delta}"
        return (f"https://mapas.fomento.gob.es/VisorSIU/"
                f"?lat={lat}&lon={lon}&zoom=15")


# ═══════════════════════════════════════════════════════════
# 3. IDEALISTA API MODULE
# ═══════════════════════════════════════════════════════════

class IdealistaAPI:
    """
    Idealista API client.

    Registration: https://developers.idealista.com/access-request
    Docs: provided after API key approval
    Free tier: 100 requests/month

    If no API key: returns empty and falls back to INE data.
    """

    TOKEN_URL = "https://api.idealista.com/oauth/token"
    SEARCH_URL = "https://api.idealista.com/3.5/es/search"

    @classmethod
    def _get_token(cls) -> Optional[str]:
        """Get OAuth2 bearer token."""
        if not IDEALISTA_API_KEY or not IDEALISTA_API_SECRET:
            return None
        try:
            resp = requests.post(
                cls.TOKEN_URL,
                auth=(IDEALISTA_API_KEY, IDEALISTA_API_SECRET),
                data={"grant_type": "client_credentials"},
                timeout=10,
            )
            if resp.status_code == 200:
                return resp.json().get("access_token")
            return None
        except:
            return None

    @classmethod
    def search(cls, lat: float, lon: float,
               distance_m: int = 1000,
               property_type: str = "homes",
               operation: str = "sale",
               build_type: str = None,
               max_items: int = 50) -> Dict:
        """
        Search Idealista listings near coordinates.

        build_type: "newDevelopment", "secondHand", or None (both)

        Returns dict with listings and stats.
        """
        token = cls._get_token()
        if not token:
            return {"status": "no_api_key",
                    "message": "Idealista API key not configured. "
                               "Using INE/Registradores fallback.",
                    "fallback": True}

        params = {
            "center": f"{lat},{lon}",
            "distance": distance_m,
            "propertyType": property_type,
            "operation": operation,
            "maxItems": max_items,
            "order": "priceDown",
            "locale": "es",
            "country": "es",
        }
        if build_type:
            params["buildType"] = build_type

        headers = {"Authorization": f"Bearer {token}"}

        try:
            resp = requests.post(cls.SEARCH_URL, data=params,
                                headers=headers, timeout=15)
            if resp.status_code == 200:
                data = resp.json()
                listings = data.get("elementList", [])

                prices_m2 = [l["priceByArea"] for l in listings
                            if "priceByArea" in l]
                sizes = [l["size"] for l in listings if "size" in l]

                return {
                    "status": "ok",
                    "total": data.get("total", 0),
                    "listings_returned": len(listings),
                    "precio_m2_medio": round(sum(prices_m2)/len(prices_m2)) if prices_m2 else 0,
                    "precio_m2_mediana": round(sorted(prices_m2)[len(prices_m2)//2]) if prices_m2 else 0,
                    "tamaño_medio_m2": round(sum(sizes)/len(sizes)) if sizes else 0,
                    "rango_precios_m2": (min(prices_m2), max(prices_m2)) if prices_m2 else (0, 0),
                    "source": "Idealista API",
                    "raw_listings": listings[:5],  # Sample for debugging
                }
            return {"status": "error", "code": resp.status_code}
        except Exception as e:
            return {"status": "error", "message": str(e)}


# ═══════════════════════════════════════════════════════════
# 4. INE PRICE DATA MODULE (public, no auth)
# ═══════════════════════════════════════════════════════════

class INEPrices:
    """
    INE official price data.
    API docs: https://www.ine.es/dyngs/DataLab/manual.html

    All endpoints are public, free, no authentication needed.
    """

    BASE = "https://servicios.ine.es/wstempus/js/ES"

    @staticmethod
    def parse_ipv(data: List[Dict]) -> Dict:
        """Turn a raw Tempus ``DATOS_TABLA`` payload into ``{series: {name: [...]}}``.

        Pure function (no network) so the real payload shape can be unit-tested.
        Each value carries ``year``, ``quarter`` (``T1``..``T4`` from
        :func:`ine_period_label`), ``period_start`` (``YYYY-MM-DD`` from
        ``Fecha``) and ``value``. ``unlabelled_periods`` counts records whose
        period could not be resolved so a caller can refuse to date the data.
        """
        series: Dict[str, List[Dict]] = {}
        unlabelled = 0
        for item in data or []:
            name = item.get("Nombre", "")
            values = []
            for d in item.get("Data", []) or []:
                if d.get("Valor") is None:
                    continue
                label = ine_period_label(d)
                if not label:
                    unlabelled += 1
                values.append({
                    "year": d.get("Anyo"),
                    "quarter": label,
                    "period_start": ine_period_start_iso(d),
                    "value": d["Valor"],
                })
            if values:
                series[name[:80]] = values
        return {"status": "ok", "series_count": len(series), "series": series,
                "unlabelled_periods": unlabelled}

    @classmethod
    def ipv_url(cls, periods: int = 8, table: Optional[str] = None) -> str:
        """Tempus URL of the IPV table (``INE_IPV_TABLE`` unless overridden)."""
        return f"{cls.BASE}/DATOS_TABLA/{table or INE_IPV_TABLE}?nult={periods}"

    @classmethod
    def get_ipv(cls, periods: int = 8, table: Optional[str] = None) -> Dict:
        """
        Get Índice de Precios de Vivienda (Housing Price Index).
        Table :data:`INE_IPV_TABLE` (80270, base 2025): quarterly by CCAA,
        general / new / second-hand, index level and variation rates.

        Returns up to ``periods`` quarters of data. Live-verified 2026-09-16
        (latest period 2026 T2). v13..v16.0.1 read 25171, the base-2015 table
        that INE stopped at 2025 T4; see :data:`INE_IPV_TABLE_LEGACY_BASE2015`.
        The result carries ``table`` so a snapshot shows which id it came from.
        """
        table = table or INE_IPV_TABLE
        url = cls.ipv_url(periods, table)
        try:
            resp = requests.get(url, timeout=15)
            if resp.status_code != 200:
                return {"status": "error", "code": resp.status_code, "table": table}
            parsed = cls.parse_ipv(resp.json())
            parsed["table"] = table
            parsed["base"] = INE_IPV_BASE_YEAR if table == INE_IPV_TABLE else ""
            return parsed
        except Exception as e:
            return {"status": "error", "message": str(e), "table": table}

    # v19 (B4): ``get_avg_price_m2`` (table 3459, HTTP 404 since v16) was removed —
    # not resurrected — because Registradores (real transaction EUR/m2) and
    # MIVAU (appraisal EUR/m2) already cover price per m2. Nothing referenced it.

    # Geo label -> series prefix as INE writes it in table 6150 (verified live).
    ETDP_GEO_LABELS = {
        "nacional": "Total Nacional", "andalucia": "Andalucía", "aragon": "Aragón",
        "asturias": "Asturias, Principado de", "baleares": "Balears, Illes", "canarias": "Canarias",
        "cantabria": "Cantabria", "castilla_leon": "Castilla y León",
        "castilla_mancha": "Castilla - La Mancha", "cataluña": "Cataluña",
        "valencia": "Comunitat Valenciana", "extremadura": "Extremadura", "galicia": "Galicia",
        "madrid": "Madrid, Comunidad de", "murcia": "Murcia, Región de",
        "navarra": "Navarra, Comunidad Foral de", "pais_vasco": "País Vasco", "rioja": "Rioja, La",
        "ceuta": "Ceuta", "melilla": "Melilla",
    }
    ETDP_SERIES = ("General", "Vivienda nueva", "Vivienda segunda mano",
                   "Vivienda libre", "Vivienda protegida")

    @classmethod
    def transactions_url(cls, periods: int = 12, table: Optional[str] = None) -> str:
        """Tempus URL of the ETDP sales table (:data:`INE_ETDP_COMPRAVENTAS_TABLE`)."""
        return f"{cls.BASE}/DATOS_TABLA/{table or INE_ETDP_COMPRAVENTAS_TABLE}?nult={periods}"

    @staticmethod
    def parse_transactions(data: List[Dict], geo_label: str) -> Dict:
        """Pick the ``<geo>. <serie>. Compraventa. Número.`` series of a 6150 payload (pure).

        Returns ``{"status": "ok", "geo": label, "series": {serie: [{"year",
        "month", "period", "period_start", "value"}...]}, "latest": {...}}`` or
        ``{"status": "error", ...}`` when the geo has no series (never a fallback
        to another geography).
        """
        wanted = {f"{geo_label}. {s}. Compraventa. Número.".lower(): s for s in INEPrices.ETDP_SERIES}
        series: Dict[str, List[Dict]] = {}
        for item in data or []:
            name = re.sub(r"\s+", " ", str(item.get("Nombre", ""))).strip().lower()
            serie = wanted.get(name)
            if serie is None:
                continue
            values = []
            for d in item.get("Data", []) or []:
                if d.get("Valor") is None:
                    continue
                label = ine_period_label(d)
                values.append({"year": d.get("Anyo"), "month": label,
                               "period": f"{d.get('Anyo')} {label}".strip(),
                               "period_start": ine_period_start_iso(d), "value": d["Valor"]})
            values.sort(key=lambda v: (v["period_start"], v["period"]))
            if values:
                series[serie] = values
        if "General" not in series:
            return {"status": "error", "geo": geo_label,
                    "message": f"no 'General' compraventa series for {geo_label!r} in payload"}
        latest = series["General"][-1]
        return {"status": "ok", "geo": geo_label, "series": series, "latest": latest,
                "series_count": len(series)}

    @classmethod
    def get_transactions(cls, periods: int = 12, ccaa: str = "nacional") -> Dict:
        """Monthly housing SALES counts (compraventas) for a CCAA — INE ETDP table 6150 (v19).

        Replaces the dead table 6171. ``ccaa`` is a key of :data:`ETDP_GEO_LABELS`
        (``"nacional"`` default). Live-verified 2026-09-16: latest period 2026 M06
        (Total Nacional General 59 288; Madrid, Comunidad de 7 056; Cataluña 9 453).
        ``{"status": "error"}`` on HTTP/JSON failure or unknown key — no guess.
        """
        geo = cls.ETDP_GEO_LABELS.get((ccaa or "nacional").strip().lower())
        if geo is None:
            return {"status": "error", "message": f"unknown ccaa key {ccaa!r}",
                    "table": INE_ETDP_COMPRAVENTAS_TABLE}
        url = cls.transactions_url(periods)
        try:
            resp = requests.get(url, timeout=20)
        except Exception as e:
            return {"status": "error", "message": f"{type(e).__name__}: {e}",
                    "table": INE_ETDP_COMPRAVENTAS_TABLE, "url": url}
        if resp.status_code != 200:
            return {"status": "error", "code": resp.status_code,
                    "table": INE_ETDP_COMPRAVENTAS_TABLE, "url": url}
        try:
            payload = resp.json()
        except ValueError:
            return {"status": "error", "message": "non-JSON body",
                    "table": INE_ETDP_COMPRAVENTAS_TABLE, "url": url}
        parsed = cls.parse_transactions(payload if isinstance(payload, list) else [], geo)
        parsed.update({"table": INE_ETDP_COMPRAVENTAS_TABLE, "url": url, "ccaa": ccaa,
                       "unit": "número de compraventas de viviendas (mensual)"})
        return parsed


class RegistradoresPrices:
    """Colegio de Registradores open-data: real notarized residential sale prices.

    Portal: https://www.registradores.org/actualidad/portal-estadistico-registral
    -> "Portal de datos abiertos" (https://opendata.registradores.org). Public,
    free, no authentication. The dataset is a single flat CSV, ``;``-separated,
    covering Spain ("Nacional"), each CCAA ("Comunidad") and each province
    ("Provincia") from 2007 to the latest published quarter. ``viv-pm2`` is the
    real transaction price per m² of residential sales registered that quarter
    — a genuine notarized-transaction price, distinct from INE's IPV (an index)
    and from Idealista (asking prices). Live-verified 2026-09-16: latest row
    2026 T2 (national and per-CCAA), e.g. Comunidad de Madrid ``viv-pm2`` =
    4305 EUR/m2. This is the source the module docstring's item 5
    ("Registradores — quarterly price reports") and ``get_transactions``'s dead
    INE table 6171 (404, documented above) were both standing in for.
    """

    URL = REGISTRADORES_COMPRAVENTAS_URL
    DATASET_PAGE = REGISTRADORES_DATASET_PAGE

    @staticmethod
    def looks_like_csv(text: str) -> bool:
        """True when the body starts with the expected header (pure).

        The WAF answers HTTP **200** with an HTML "Request Rejected" page; that
        body must never reach ``parse_csv`` as if it were data.
        """
        first = (text or "").lstrip(" \r\n").split("\n", 1)[0].lower()
        return first.startswith("ano;trim;")

    @staticmethod
    def parse_csv(text: str) -> List[Dict]:
        """Parse the ``;``-separated CSV into typed rows (pure function, no network).

        Numeric fields use a comma decimal separator in the earliest years
        (``"1961,66"``) and plain integers in later ones (``"4305"``); both are
        handled. A missing/malformed numeric field becomes ``None`` — never a
        silent ``0.0`` that would read as a real (if tiny) price.
        """
        rows: List[Dict] = []
        lines = (text or "").splitlines()
        if not lines:
            return rows
        header = [h.strip() for h in lines[0].split(";")]
        int_fields = ("ano", "trim", "cod-ca", "cod-prv")
        float_fields = ("viv-num", "viv-imp", "viv-pm2", "gar-num", "gar-imp",
                        "gar-pm2", "tras-num", "tras-imp", "tras-pm2")
        for line in lines[1:]:
            if not line.strip():
                continue
            cells = line.split(";")
            row = dict(zip(header, cells))
            for key in int_fields:
                try:
                    row[key] = int(row.get(key) or "")
                except (TypeError, ValueError):
                    row[key] = None
            for key in float_fields:
                raw = (row.get(key) or "").strip().replace(",", ".")
                try:
                    row[key] = float(raw) if raw else None
                except ValueError:
                    row[key] = None
            rows.append(row)
        return rows

    @classmethod
    def _download_csv(cls, url: str) -> Tuple[str, str]:
        """``(text, "")`` for a real CSV body, else ``("", error)``."""
        try:
            resp = requests.get(url, headers=REGISTRADORES_HEADERS, timeout=30)
        except Exception as e:
            return "", f"{type(e).__name__}: {e}"
        if resp.status_code != 200:
            return "", f"HTTP {resp.status_code}"
        text = resp.content.decode("utf-8-sig", "replace")
        if not cls.looks_like_csv(text):
            hint = "WAF 'Request Rejected' page" if "Request Rejected" in text else "not the expected CSV header"
            return "", f"HTTP 200 but body is {hint}"
        return text, ""

    @classmethod
    def resolve_csv_url(cls) -> Dict:
        """Return the URL that currently serves the CSV and how it was found.

        1. the pinned :data:`REGISTRADORES_COMPRAVENTAS_URL`; 2. if that fails
        (404 once the next quarter is published, or a WAF/HTML body), the
        dataset page is read and the newest ``RP_ComprvResid_*.csv`` link is
        followed. ``{"status": "ok", "url", "text", "resolved_via"}`` or
        ``{"status": "error", "message", "url"}`` listing both failures.
        """
        text, error = cls._download_csv(cls.URL)
        if text:
            return {"status": "ok", "url": cls.URL, "text": text, "resolved_via": "pinned"}
        pinned_error = f"pinned URL: {error}"
        try:
            page = requests.get(cls.DATASET_PAGE, headers=REGISTRADORES_HEADERS, timeout=30)
        except Exception as e:
            return {"status": "error", "url": cls.URL,
                    "message": f"{pinned_error}; dataset page: {type(e).__name__}: {e}"}
        if page.status_code != 200:
            return {"status": "error", "url": cls.URL,
                    "message": f"{pinned_error}; dataset page: HTTP {page.status_code}"}
        discovered = discover_registradores_csv_url(page.text)
        if not discovered:
            return {"status": "error", "url": cls.URL,
                    "message": f"{pinned_error}; dataset page links no RP_ComprvResid_*.csv"}
        if discovered == cls.URL:
            return {"status": "error", "url": cls.URL,
                    "message": f"{pinned_error}; dataset page links the same file"}
        text, error = cls._download_csv(discovered)
        if not text:
            return {"status": "error", "url": discovered,
                    "message": f"{pinned_error}; discovered {discovered}: {error}"}
        return {"status": "ok", "url": discovered, "text": text, "resolved_via": "dataset_page"}

    @classmethod
    def get_compraventas(cls, ccaa: str = "nacional") -> Dict:
        """Download the dataset and return the latest quarter for ``ccaa``.

        ``ccaa`` is one of the internal keys in :data:`REGISTRADORES_CCAA_NAMES`
        (or ``"nacional"``). Returns ``{"status": "ok", "ccaa", "label", "geo",
        "latest": {...row...}, "series": [...all periods, oldest first...],
        "url", "resolved_via", "dataset_latest_period",
        "latest_row_without_price"}`` or ``{"status": "error", ...}`` on any
        HTTP/parse/lookup failure — never a silently empty or zero-filled row.

        v18 round 5: the pinned filename is discovered from the dataset page
        when it stops working; an HTML body is rejected before parsing; the
        header must carry :data:`REGISTRADORES_REQUIRED_COLUMNS`; ``latest`` is
        the newest row **with a price** (a published quarter whose ``viv-pm2``
        is empty is reported through ``latest_row_without_price``, not as a
        price).
        """
        label = REGISTRADORES_CCAA_NAMES.get(ccaa)
        if not label:
            return {"status": "error", "message": f"unknown ccaa key {ccaa!r}", "url": cls.URL}
        geo = "Nacional" if ccaa == "nacional" else "Comunidad"
        resolved = cls.resolve_csv_url()
        if resolved["status"] != "ok":
            return {"status": "error", "message": resolved["message"], "url": resolved["url"]}
        text, url = resolved["text"], resolved["url"]
        header = [h.strip() for h in text.lstrip(" \r\n").split("\n", 1)[0].split(";")]
        missing = [c for c in REGISTRADORES_REQUIRED_COLUMNS if c not in header]
        if missing:
            return {"status": "error", "url": url,
                    "message": f"CSV schema changed: missing column(s) {missing}; header={header[:8]}"}
        rows = cls.parse_csv(text)
        all_periods = [(r["ano"], r["trim"]) for r in rows if r.get("ano") and r.get("trim")]
        dataset_latest = max(all_periods) if all_periods else None
        series = [r for r in rows if r.get("geo") == geo and r.get("ca") == label]
        if not series:
            return {"status": "error", "message": f"no rows for {label!r} ({geo})", "url": url}
        series.sort(key=lambda r: (r.get("ano") or 0, r.get("trim") or 0))
        priced = [r for r in series if r.get("viv-pm2") is not None]
        if not priced:
            return {"status": "error", "url": url,
                    "message": f"rows for {label!r} carry no viv-pm2 price at all"}
        latest = priced[-1]
        return {"status": "ok", "ccaa": ccaa, "label": label, "geo": geo,
                "latest": latest, "series": series, "url": url,
                "resolved_via": resolved["resolved_via"],
                "dataset_latest_period": f"{dataset_latest[0]} T{dataset_latest[1]}" if dataset_latest else "",
                "latest_row_without_price": latest is not series[-1]}


class MivauPrices:
    """Ministerio de Vivienda y Agenda Urbana (ex-Fomento) "Boletín Estadístico Online" tables (v18).

    ``apps.fomento.gob.es/BoletinOnline2/`` publishes, per statistical
    programme (``?nivel=2&orden=34000000`` transacciones, ``35000000`` valor
    tasado), binary Excel 97 files ``sedal/<id>.XLS`` (OLE2/BIFF, verified
    2026-09-16). Two are wired, each with a precise meaning:

    - ``valor_tasado_vivienda_libre`` (Tabla 1.1, ``sedal/35101500.XLS``,
      **EUR/m2**): mean *appraisal* value of free-market dwellings from the
      ECO/805 valuation reports of the tasadoras. Quarterly, CCAA and province,
      2010-present (latest sheet 2024-2026, "1º" of 2026 present on
      2026-09-16; file last modified 2026-05-28). An appraisal is not a sale:
      it cross-checks the Registradores transaction EUR/m2 but never replaces it.
    - ``valor_medio_transaccion_vivienda_libre`` (Tabla 3.3.1,
      ``sedal/34020160.XLS``, **EUR per transaction**): mean declared value of
      each notarised free-housing sale (the Ministry's own transactions
      statistic, from notarial data). It is a value per dwelling, NOT per m2,
      so it must never be compared with EUR/m2 figures. Quarterly, 2004-present
      (2026 "1º (**)" provisional on 2026-09-16; file last modified 2026-06-11).

    Sheet layout (identical in both files): sheets of 4-5 years ("2024, 2025,
    2026"); row 12 ``Año YYYY`` over four quarter columns, row 14 ``1º..4º``
    (``(**)`` = provisional), rows 15+ one region per row with the label in
    column B (``TOTAL NACIONAL``, CCAA, then its provinces); ``n.r`` = not
    reported; the valor tasado sheet appends ``Variación`` columns that are
    ignored. :meth:`parse_sheet` is pure over ``list[list]`` rows so it is
    tested without Excel; :meth:`load_xls_sheets` needs the optional ``xlrd``
    package (``pip install xlrd`` / extra ``[mivau]``) — without it the
    collector reports ``SKIPPED`` and says so, it never guesses.
    """

    BASE = "https://apps.fomento.gob.es/BoletinOnline2/"
    TABLES = {
        "valor_tasado_vivienda_libre": {
            "file": "sedal/35101500.XLS",
            "title": "Valor tasado medio de vivienda libre (Boletín Estadístico MIVAU, Tabla 1.1)",
            "unit": "EUR/m2",
            "role": "appraisal_price_m2",
            "nature": "mean ECO/805 appraisal value reported by valuation companies — "
                      "an appraisal, NOT a transaction price and NOT an asking price",
            "programme_url": BASE + "?nivel=2&orden=35000000",
        },
        "valor_medio_transaccion_vivienda_libre": {
            "file": "sedal/34020160.XLS",
            "title": "Valor medio de las transacciones inmobiliarias de vivienda libre "
                     "(Boletín Estadístico MIVAU, Tabla 3.3.1)",
            "unit": "EUR per transaction",
            "role": "transaction_value_avg",
            "nature": "mean declared value per notarised sale of a free-market dwelling — "
                      "a value per dwelling, NOT per m2; not comparable with EUR/m2 series",
            "programme_url": BASE + "?nivel=2&orden=34000000",
        },
    }
    # Row labels as printed in column B (normalised: lower-case, accents
    # stripped). Both spellings of Valencia occur (one per table).
    CCAA_LABELS = {
        "nacional": ("total nacional",), "andalucia": ("andalucia",), "aragon": ("aragon",),
        "asturias": ("asturias (principado de )", "asturias (principado de)"),
        "baleares": ("balears (illes)",), "canarias": ("canarias",), "cantabria": ("cantabria",),
        "castilla_leon": ("castilla y leon",), "castilla_mancha": ("castilla-la mancha",),
        "cataluña": ("cataluna",), "valencia": ("comunidad valenciana", "comunitat valenciana"),
        "extremadura": ("extremadura",), "galicia": ("galicia",), "madrid": ("madrid (comunidad de)",),
        "murcia": ("murcia (region de)",), "navarra": ("navarra (comunidad foral de)",),
        "pais_vasco": ("pais vasco",), "rioja": ("rioja (la)",), "ceuta": ("ceuta",), "melilla": ("melilla",),
    }
    # apps.fomento.gob.es accepts the project's own User-Agent (verified live
    # 2026-09-16: HTTP 200 application/vnd.ms-excel, OLE2 magic) — no browser
    # impersonation needed here, unlike opendata.registradores.org.
    HEADERS = {"User-Agent": "RailNexus-MarketIntelligence (+https://value.railnexus.io)"}

    @staticmethod
    def _cell_value(cell) -> Optional[float]:
        if isinstance(cell, bool):
            return None
        if isinstance(cell, (int, float)):
            return float(cell)
        text = str(cell or "").strip().replace(",", ".")
        if not text or text.lower() in ("n.r", "n.r.", "-", "--", "nd", "n.d."):
            return None
        try:
            return float(text)
        except ValueError:
            return None

    @staticmethod
    def parse_sheet(rows: List[List]) -> Dict:
        """Parse one sheet (list of row lists) into ``{"periods", "provisional", "series"}`` (pure).

        ``periods`` are ``"YYYY Tn"`` labels in column order; ``provisional``
        is the subset marked ``(*`` in the quarter header; ``series`` maps the
        raw region label to a list of values aligned with ``periods`` (``None``
        for ``n.r`` / blank). Returns empty structures when the ``Año`` header
        row is not found (layout change) — never a guessed alignment.
        """
        empty = {"periods": [], "provisional": [], "series": {}}
        year_row = quarter_row = None
        for i, row in enumerate(rows):
            if any(re.match(r"^\s*Año\s+\d{4}", str(c or "")) for c in row):
                year_row = i
                break
        if year_row is None:
            return empty
        for j in range(year_row + 1, min(year_row + 4, len(rows))):
            if any(re.match(r"^\s*[1-4]º", str(c or "")) for c in rows[j]):
                quarter_row = j
                break
        if quarter_row is None:
            return empty
        columns: List[Tuple[int, str, bool]] = []
        year = None
        for col, head in enumerate(rows[year_row]):
            head = str(head or "").strip()
            match = re.match(r"^Año\s+(\d{4})", head)
            if match:
                year = int(match.group(1))
            elif head:            # "Variación" and other non-year headers end the year span
                year = None
            quarter = str(rows[quarter_row][col] if col < len(rows[quarter_row]) else "").strip()
            qmatch = re.match(r"^([1-4])º", quarter)
            if year and qmatch:
                columns.append((col, f"{year} T{qmatch.group(1)}", "(*" in quarter))
        if not columns:
            return empty
        label_col = None
        series: Dict[str, List[Optional[float]]] = {}
        for row in rows[quarter_row + 1:]:
            cells = list(row)
            if label_col is None:
                for col, cell in enumerate(cells):
                    if str(cell or "").strip():
                        label_col = col
                        break
                if label_col is None:
                    continue
            label = str(cells[label_col] if label_col < len(cells) else "").strip()
            if not label:
                continue
            if label.startswith(("*", "(")):
                break
            series[label] = [MivauPrices._cell_value(cells[c]) if c < len(cells) else None
                             for c, _, _ in columns]
        return {"periods": [p for _, p, _ in columns],
                "provisional": [p for _, p, prov in columns if prov],
                "series": series}

    @staticmethod
    def merge_sheets(parsed_sheets: List[Dict]) -> Dict:
        """Merge per-sheet results into one chronological table (pure; later sheets win)."""
        periods: Dict[str, bool] = {}
        series: Dict[str, Dict[str, Optional[float]]] = {}
        for sheet in parsed_sheets:
            prov = set(sheet.get("provisional") or [])
            for p in sheet.get("periods") or []:
                periods[p] = p in prov
            for label, values in (sheet.get("series") or {}).items():
                series.setdefault(label, {})
                for p, v in zip(sheet.get("periods") or [], values):
                    series[label][p] = v
        ordered = sorted(periods, key=lambda p: (int(p[:4]), int(p[-1])))
        return {"periods": ordered,
                "provisional": [p for p in ordered if periods[p]],
                "series": {label: [vals.get(p) for p in ordered] for label, vals in series.items()}}

    @staticmethod
    def load_xls_sheets(content: bytes) -> List[List[List]]:
        """Return every sheet of a BIFF workbook as row lists (needs ``xlrd``)."""
        import xlrd  # optional dependency; ImportError handled by get_table
        book = xlrd.open_workbook(file_contents=content)
        return [[sheet.row_values(i) for i in range(sheet.nrows)] for sheet in book.sheets()]

    @classmethod
    def find_label(cls, series: Dict, ccaa: str) -> str:
        """Row label of ``ccaa`` inside ``series`` (exact normalised match first, then prefix)."""
        wanted = cls.CCAA_LABELS.get(ccaa) or ()
        norm = {_normalize(label).strip(): label for label in series}
        for candidate in wanted:
            if candidate in norm:
                return norm[candidate]
        for candidate in wanted:
            for key, label in norm.items():
                if key.startswith(candidate):
                    return label
        return ""

    @classmethod
    def get_table(cls, table_key: str, ccaa: str = "nacional") -> Dict:
        """Download one table and return the series for ``ccaa``.

        ``{"status": "ok", "table", "title", "unit", "role", "nature", "url",
        "last_modified", "ccaa", "label", "periods", "provisional", "latest":
        {"period", "value", "provisional"}, "series": [...]}``;
        ``{"status": "skipped", "message"}`` when ``xlrd`` is missing;
        ``{"status": "error", "message"}`` for HTTP / layout / lookup failures.
        """
        spec = cls.TABLES.get(table_key)
        if not spec:
            return {"status": "error", "message": f"unknown MIVAU table {table_key!r}"}
        if ccaa not in cls.CCAA_LABELS:
            return {"status": "error", "message": f"unknown ccaa key {ccaa!r}", "url": cls.BASE + spec["file"]}
        url = cls.BASE + spec["file"]
        try:
            import xlrd  # noqa: F401
        except ImportError:
            # v19: xlrd is a HARD dependency (pyproject ``dependencies``); its
            # absence is a broken environment, reported as an error — not the
            # "expected SKIPPED" it was while the package was optional.
            return {"status": "error", "url": url, "table": table_key,
                    "message": "xlrd is not installed — it is a required dependency since v19 "
                               "(the MIVAU tables are binary Excel 97 .XLS files); reinstall the "
                               "package (pip install .) or pip install 'xlrd>=2.0,<3'"}
        try:
            resp = requests.get(url, headers=cls.HEADERS, timeout=60)
        except Exception as e:
            return {"status": "error", "message": f"{type(e).__name__}: {e}", "url": url}
        if resp.status_code != 200:
            return {"status": "error", "code": resp.status_code, "url": url}
        if resp.content[:8] != b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1":
            return {"status": "error", "url": url,
                    "message": "body is not an OLE2/BIFF workbook (format change or error page)"}
        try:
            sheets = cls.load_xls_sheets(resp.content)
        except Exception as e:
            return {"status": "error", "message": f"workbook unreadable: {type(e).__name__}: {e}", "url": url}
        merged = cls.merge_sheets([cls.parse_sheet(rows) for rows in sheets])
        if not merged["periods"]:
            return {"status": "error", "url": url,
                    "message": "no 'Año YYYY' / '1º..4º' header found in any sheet (layout changed)"}
        label = cls.find_label(merged["series"], ccaa)
        if not label:
            return {"status": "error", "url": url,
                    "message": f"no row for {ccaa!r} (labels: {list(merged['series'])[:6]}...)"}
        values = merged["series"][label]
        points = [{"period": p, "value": v, "provisional": p in merged["provisional"]}
                  for p, v in zip(merged["periods"], values)]
        priced = [pt for pt in points if pt["value"] is not None]
        if not priced:
            return {"status": "error", "url": url, "message": f"row {label!r} has no numeric value"}
        return {"status": "ok", "table": table_key, "title": spec["title"], "unit": spec["unit"],
                "role": spec["role"], "nature": spec["nature"], "url": url,
                "programme_url": spec["programme_url"],
                "last_modified": resp.headers.get("Last-Modified", ""),
                "ccaa": ccaa, "label": label, "periods": merged["periods"],
                "provisional": merged["provisional"], "latest": priced[-1], "series": points}


# ═══════════════════════════════════════════════════════════
# 5. REFERENCE MARKET DATA (fallback when APIs unavailable)
# ═══════════════════════════════════════════════════════════

REFERENCE_MARKET_DATA = {
    "valencia": {
        "precio_m2_nueva": 2950,
        "precio_m2_segunda": 2380,
        "precio_m2_promedio": 2620,
        "tamaño_medio_nueva": 115,
        "tamaño_medio_segunda": 88,
        "variacion_anual_pct": 14.8,
        "variacion_2_años_pct": 28.5,
        "compraventas_trimestre": 4850,
        "stock_nueva": 2340,
        "fecha": "Q4 2025",
        "fuentes": ["INE IPV Q4 2025", "Registradores Q4 2025"],
    },
    "barcelona": {
        "precio_m2_nueva": 5200,
        "precio_m2_segunda": 4150,
        "precio_m2_promedio": 4580,
        "tamaño_medio_nueva": 95,
        "tamaño_medio_segunda": 78,
        "variacion_anual_pct": 11.2,
        "variacion_2_años_pct": 22.8,
        "compraventas_trimestre": 5120,
        "stock_nueva": 1890,
        "fecha": "Q4 2025",
        "fuentes": ["INE IPV Q4 2025", "Registradores Q4 2025"],
    },
    "madrid": {
        "precio_m2_nueva": 5700,
        "precio_m2_segunda": 4350,
        "precio_m2_promedio": 4920,
        "tamaño_medio_nueva": 105,
        "tamaño_medio_segunda": 82,
        "variacion_anual_pct": 16.5,
        "variacion_2_años_pct": 32.1,
        "compraventas_trimestre": 12340,
        "stock_nueva": 4560,
        "fecha": "Q4 2025",
        "fuentes": ["INE IPV Q4 2025", "Registradores Q4 2025"],
    },
    "sevilla": {
        "precio_m2_nueva": 2650,
        "precio_m2_segunda": 1980,
        "precio_m2_promedio": 2250,
        "tamaño_medio_nueva": 110,
        "tamaño_medio_segunda": 92,
        "variacion_anual_pct": 10.3,
        "variacion_2_años_pct": 19.5,
        "compraventas_trimestre": 3240,
        "stock_nueva": 1670,
        "fecha": "Q4 2025",
        "fuentes": ["INE IPV Q4 2025", "Registradores Q4 2025"],
    },
    "malaga": {
        "precio_m2_nueva": 3400,
        "precio_m2_segunda": 2650,
        "precio_m2_promedio": 2980,
        "tamaño_medio_nueva": 100,
        "tamaño_medio_segunda": 85,
        "variacion_anual_pct": 18.2,
        "variacion_2_años_pct": 35.4,
        "compraventas_trimestre": 4120,
        "stock_nueva": 2890,
        "fecha": "Q4 2025",
        "fuentes": ["INE IPV Q4 2025", "Registradores Q4 2025"],
    },
}


# ═══════════════════════════════════════════════════════════
# 6. PRICE PROJECTION ENGINE
# ═══════════════════════════════════════════════════════════

class PriceProjector:
    """
    Project prices 6 and 12 months forward based on historical trends.

    Methods:
    1. Compound growth from last 2 years annual rate
    2. Linear regression on quarterly data (if available)
    3. Weighted average (recent quarters weighted more)
    """

    @staticmethod
    def compound_projection(current_price: float,
                            annual_growth_pct: float,
                            months: int = 6) -> float:
        """Simple compound growth projection."""
        monthly_rate = (1 + annual_growth_pct / 100) ** (1/12) - 1
        return round(current_price * (1 + monthly_rate) ** months, 2)

    @staticmethod
    def from_quarterly_data(quarterly_values: List[float],
                            current_price: float,
                            months_forward: int = 6) -> Dict:
        """
        Project from quarterly index values.
        Uses weighted linear regression (recent data weighted 2x).

        quarterly_values: list of quarterly % changes, oldest first
        """
        if len(quarterly_values) < 4:
            return {"projection": current_price,
                    "confidence": "baja",
                    "method": "insufficient_data"}

        n = len(quarterly_values)
        # Weighted: most recent quarters count double
        weights = [1.0] * (n - 2) + [2.0, 2.0]
        weighted_avg_quarterly = (
            sum(v * w for v, w in zip(quarterly_values, weights))
            / sum(weights)
        )

        # Annualize
        annual_rate = (1 + weighted_avg_quarterly / 100) ** 4 - 1
        monthly_rate = (1 + annual_rate) ** (1/12) - 1
        projected = current_price * (1 + monthly_rate) ** months_forward

        # Confidence based on variance
        variance = sum((v - weighted_avg_quarterly) ** 2
                      for v in quarterly_values) / n
        std_dev = math.sqrt(variance)

        if std_dev < 2:
            confidence = "alta"
        elif std_dev < 5:
            confidence = "media"
        else:
            confidence = "baja"

        return {
            "projection": round(projected, 2),
            "annual_rate_pct": round(annual_rate * 100, 1),
            "quarterly_avg_pct": round(weighted_avg_quarterly, 2),
            "confidence": confidence,
            "method": "weighted_linear_regression",
            "std_dev": round(std_dev, 2),
        }

    @staticmethod
    def full_projection(market: MarketPrice,
                        annual_growth: float,
                        quarterly_data: List[float] = None) -> PriceTrend:
        """
        Generate full price trend with projections.
        Combines compound growth with quarterly regression if available.
        """
        # Use quarterly data if available, otherwise compound
        # ``metodo`` and ``confianza`` are language-neutral CODES; the report
        # localises them via TEXT (v15 stored Catalan sentences here).
        if quarterly_data and len(quarterly_data) >= 4:
            proj_nueva = PriceProjector.from_quarterly_data(
                quarterly_data, market.precio_m2_nueva, 6)
            proj_segunda = PriceProjector.from_quarterly_data(
                quarterly_data, market.precio_m2_segunda, 6)
            proj_12m = PriceProjector.from_quarterly_data(
                quarterly_data, market.precio_m2_nueva, 12)
            method = "ine_weighted_regression"
            confidence = {"alta": "high", "media": "medium", "baja": "low"}.get(
                proj_nueva["confidence"], "low")
        else:
            proj_nueva = {"projection": PriceProjector.compound_projection(
                market.precio_m2_nueva, annual_growth, 6)}
            proj_segunda = {"projection": PriceProjector.compound_projection(
                market.precio_m2_segunda, annual_growth, 6)}
            proj_12m = {"projection": PriceProjector.compound_projection(
                market.precio_m2_nueva, annual_growth, 12)}
            method = "compound_trend"
            confidence = "medium"

        # Determine trend
        if annual_growth > 5:
            tendencia = "alcista"
        elif annual_growth > -2:
            tendencia = "estable"
        else:
            tendencia = "bajista"

        return PriceTrend(
            variacion_trimestral=quarterly_data or [],
            variacion_anual_pct=annual_growth,
            variacion_2_años_pct=0,  # filled by caller
            tendencia=tendencia,
            proyeccion_6_meses_nueva=proj_nueva["projection"],
            proyeccion_6_meses_segunda=proj_segunda["projection"],
            proyeccion_12_meses_nueva=proj_12m["projection"],
            confianza=confidence,
            metodo=method,
            fuentes=[],
        )


# ═══════════════════════════════════════════════════════════
# 7. FEASIBILITY CALCULATOR
# ═══════════════════════════════════════════════════════════

class FeasibilityCalc:
    """Calculate development feasibility from market + land data."""

    @staticmethod
    def calculate(land: LandClassification, market: MarketPrice,
                  trend: PriceTrend, municipio: str = "",
                  language: str = "ca") -> Dict:
        """
        Calculate feasibility metrics.

        Returns: semáforo, margins, risks, recommendation. Every human-readable
        field is localised to ``language``; ``semaforo_code`` / ``viable_code``
        carry the language-neutral value for programmatic use.
        """
        if market.data_status != "LIVE":
            return {
                "semaforo_code": "NONE", "viable_code": "INCONCLUSIVE",
                "semaforo": tr(language, "sem_none"),
                "viable": tr(language, "viable_unverified"),
                "razon": tr(language, "reason_no_live"),
                "recomendacion": tr(language, "action_no_live"),
            }

        if land.permite_construccion is None or not land.verified_for_parcel:
            # v19 P0: zoning not verified for THIS parcel -> inconclusive, never
            # RED (we do not know it is forbidden) and never GREEN (we do not
            # know it is allowed).
            return {
                "semaforo_code": "NONE", "viable_code": "INCONCLUSIVE",
                "semaforo": tr(language, "sem_none"),
                "viable": tr(language, "viable_unverified"),
                "razon": tr(language, "reason_zoning_unverified"),
                "recomendacion": tr(language, "action_zoning_unverified"),
                "zoning_verification_status": land.verification_status,
            }

        if not land.permite_construccion:
            return {
                "semaforo_code": "RED", "viable_code": "NOT_VIABLE",
                "semaforo": tr(language, "sem_red"),
                "viable": tr(language, "viable_no_build"),
                "razon": tr(language, "reason_no_build"),
                "recomendacion": tr(language, "action_no_build"),
            }

        if trend.metodo == "no_trend_data":
            # A margin can be computed from live prices, but a 6-month projected
            # margin cannot; do not fabricate one from a default growth rate.
            proj_available = False
        else:
            proj_available = True

        # Construction cost
        muni_lower = municipio.lower()
        cost_m2 = CONSTRUCTION_COSTS.get(muni_lower,
                                          CONSTRUCTION_COSTS["default"])

        # Land cost estimate (~25-35% of final sale price)
        land_pct = 0.30
        land_cost_m2 = round(market.precio_m2_nueva * land_pct)

        # Soft costs (~15% of hard costs)
        soft_costs_m2 = round(cost_m2 * 0.15)

        # Total development cost
        total_cost_m2 = cost_m2 + land_cost_m2 + soft_costs_m2

        # Margins
        margin_m2 = market.precio_m2_nueva - total_cost_m2
        margin_pct = (margin_m2 / total_cost_m2) * 100 if total_cost_m2 > 0 else 0

        # Projected margin at 6 months (only when a real trend exists)
        if proj_available:
            proj_margin_m2 = trend.proyeccion_6_meses_nueva - total_cost_m2
            proj_margin_pct = (proj_margin_m2 / total_cost_m2) * 100 if total_cost_m2 > 0 else 0
        else:
            proj_margin_m2 = None
            proj_margin_pct = None

        # Semáforo
        if margin_pct > 20:
            code, viable_code, viable_key = "GREEN", "VIABLE", "viable_green"
        elif margin_pct > 10:
            code, viable_code, viable_key = "YELLOW", "VIABLE_CONDITIONAL", "viable_yellow"
        elif margin_pct > 0:
            code, viable_code, viable_key = "YELLOW", "MARGINAL", "viable_marginal"
        else:
            code, viable_code, viable_key = "RED", "NOT_VIABLE", "viable_red"
        semaforo = tr(language, {"GREEN": "sem_green", "YELLOW": "sem_yellow", "RED": "sem_red"}[code])

        # Risks (codes + localised description)
        risks = []
        if proj_available and trend.variacion_anual_pct > 12:
            risks.append({
                "code": "MARKET_OVERHEATING", "type": tr(language, "risk_market"), "level": "🟡",
                "desc": tr(language, "risk_overheating", pct=trend.variacion_anual_pct),
            })
        if proj_available and trend.variacion_anual_pct < 0:
            risks.append({
                "code": "MARKET_FALLING", "type": tr(language, "risk_market"), "level": "🔴",
                "desc": tr(language, "risk_falling", pct=trend.variacion_anual_pct),
            })
        if market.ratio_nueva_vs_segunda > 1.40:
            risks.append({
                "code": "NEW_BUILD_PREMIUM", "type": tr(language, "risk_competition"), "level": "🟡",
                "desc": tr(language, "risk_premium",
                           pct=f"{(market.ratio_nueva_vs_segunda-1)*100:.0f}"),
            })
        # v19: zoning caveats of a verified-but-partial answer are risks, not silence
        level = (land.raw or {}).get("verification_level", "")
        if level == "siu_clase_suelo":
            risks.append({
                "code": "ZONING_USE_UNVERIFIED", "type": tr(language, "risk_zoning"), "level": "🟡",
                "desc": tr(language, "risk_zoning_use_unverified"),
            })
        elif land.permite_residencial is None:
            risks.append({
                "code": "ZONING_RESIDENTIAL_UNKNOWN", "type": tr(language, "risk_zoning"), "level": "🟡",
                "desc": tr(language, "risk_zoning_residential_unknown",
                           calificacion=land.calificacion or "?"),
            })
        if land.clase_suelo in ("suelo_urbanizable_delimitado", "suelo_urbano_no_consolidado"):
            note = SIU_CLASE_SUELO_VERDICT.get(
                {"suelo_urbanizable_delimitado": "SUELO URBANIZABLE DELIMITADO O SECTORIZADO",
                 "suelo_urbano_no_consolidado": "SUELO URBANO NO CONSOLIDADO"}[land.clase_suelo], ("", "", ""))[2]
            risks.append({
                "code": "ZONING_REQUIRES_DEVELOPMENT", "type": tr(language, "risk_zoning"), "level": "🟡",
                "desc": tr(language, "risk_zoning_development", note=note or land.clase_suelo),
            })

        return {
            "semaforo_code": code,
            "viable_code": viable_code,
            "semaforo": semaforo,
            "viable": tr(language, viable_key),
            "costos": {
                "construccio_m2": cost_m2,
                "sol_estimat_m2": land_cost_m2,
                "costos_tous_m2": soft_costs_m2,
                "cost_total_m2": total_cost_m2,
            },
            "marges": {
                "marge_brut_m2": round(margin_m2),
                "marge_brut_pct": f"{margin_pct:.1f}%",
                "marge_projectat_6m_m2": round(proj_margin_m2) if proj_margin_m2 is not None else None,
                "marge_projectat_6m_pct": (f"{proj_margin_pct:.1f}%" if proj_margin_pct is not None
                                           else None),
            },
            "riscos": risks,
            "nota": tr(language, "cost_note"),
        }


# ═══════════════════════════════════════════════════════════
# 8. REPORT GENERATOR
# ═══════════════════════════════════════════════════════════

class MarketReportGenerator:
    """Generate complete market intelligence report."""

    @staticmethod
    def generate(report: MarketReport, language: str = "ca") -> str:
        """Generate formatted text report in ``language`` (ca/es/en) from the TEXT catalogue."""
        r = report
        L = lambda key, **fmt: tr(language, key, **fmt)  # noqa: E731
        lines = []

        lines.append("=" * 70)
        lines.append(f"  {L('report_title')}")
        lines.append("=" * 70)
        lines.append(f"  {L('address')}: {r.parcel.direccion}")
        lines.append(f"  {L('municipality')}: {r.parcel.municipio}")
        lines.append(f"  {L('cadastral_ref')}: {r.parcel.ref_catastral}")
        lines.append(f"  {L('date')}: {r.timestamp}")
        lines.append("=" * 70)

        # Land classification
        lines.append(f"\n{'─' * 70}")
        lines.append(f"  {L('section_land')}")
        lines.append(f"{'─' * 70}")
        lines.append(f"  {L('class')}: {r.land_class.clase_suelo}")
        lines.append(f"  {L('designation')}: {r.land_class.calificacion}")
        if r.land_class.permite_construccion is None or not r.land_class.verified_for_parcel:
            perm = L("unverified")
        else:
            perm = L("yes") if r.land_class.permite_construccion else L("no")
        lines.append(f"  {L('construction_allowed')}: {perm}")
        lines.append(f"  {L('current_plan')}: {r.land_class.plan_vigente}")
        lines.append(f"  {L('zoning_source')}: {r.land_class.source} "
                     f"[{r.land_class.verification_status}]")
        lines.append(f"  {r.land_class.observaciones}")
        siu_url = SIUClassifier.get_wms_url(*r.parcel.coordinates)
        lines.append(f"  {L('siu_map')}: {siu_url}")

        # Market prices
        lines.append(f"\n{'─' * 70}")
        lines.append(f"  {L('section_prices')}")
        lines.append(f"{'─' * 70}")
        m = r.market
        lines.append(f"  {L('source')}: {m.source} | {L('radius')}: {m.radio_busqueda_m}m")
        lines.append(f"  {L('data_status')}: {m.data_status}")
        if m.data_status == "NO_LIVE_MARKET_DATA":
            lines.append(f"  {L('no_live_prices')}")
            for error in m.source_errors:
                lines.append(f"  {L('source_error')}: {error}")
        else:
            if m.fecha_datos:
                lines.append(f"  {L('data_date')}: {m.fecha_datos}")
            if m.data_status == "HISTORICAL_REFERENCE":
                lines.append(f"  {L('historical_warning', date=m.fecha_datos or '?')}")
            lines.append(f"  {L('new_build')}: {m.precio_m2_nueva:>8,} €/m² "
                         f"({m.num_listings_nueva} {L('listings')}, ~{m.tamaño_medio_nueva_m2} m²)")
            lines.append(f"  {L('resale')}: {m.precio_m2_segunda:>8,} €/m² "
                         f"({m.num_listings_segunda} {L('listings')}, ~{m.tamaño_medio_segunda_m2} m²)")
            lines.append(f"  {L('area_avg')}: {m.precio_m2_promedio:>8,} €/m²")
            ratio_str = f"+{(m.ratio_nueva_vs_segunda-1)*100:.1f}%"
            lines.append(f"  {L('premium')}: {ratio_str}")

        # Projections — only from LIVE prices and a real trend series
        lines.append(f"\n{'─' * 70}")
        lines.append(f"  {L('section_projections')}")
        lines.append(f"{'─' * 70}")
        t = r.trend
        if m.data_status != "LIVE":
            lines.append(f"  {L('no_projections')}")
        elif t.metodo == "no_trend_data":
            lines.append(f"  {L('no_trend')}")
        else:
            trend_key = {"alcista": "trend_up", "estable": "trend_flat", "bajista": "trend_down"}.get(
                t.tendencia, "trend_flat")
            lines.append(f"  {L('trend')}: {L(trend_key)} ({t.variacion_anual_pct:+.1f}% {L('annual')})")
            lines.append(f"  {L('new_6m')}:   {t.proyeccion_6_meses_nueva:>8,.0f} €/m²")
            lines.append(f"  {L('new_12m')}:  {t.proyeccion_12_meses_nueva:>8,.0f} €/m²")
            lines.append(f"  {L('resale_6m')}: {t.proyeccion_6_meses_segunda:>8,.0f} €/m²")
            conf_key = {"high": "conf_high", "medium": "conf_medium", "low": "conf_low"}.get(
                t.confianza, "conf_none")
            lines.append(f"  {L('confidence')}: {L(conf_key)} | {L('method')}: {L('method_' + t.metodo)}")

        # Feasibility
        if r.feasibility:
            f = r.feasibility
            lines.append(f"\n{'─' * 70}")
            lines.append(f"  {L('section_feasibility')}")
            lines.append(f"{'─' * 70}")
            lines.append(f"  {f['semaforo']} — {f['viable']}")
            if f.get("costos") and f.get("marges"):
                c = f["costos"]
                mg = f["marges"]
                lines.append(f"\n  {L('estimated_costs')}:")
                lines.append(f"    {L('construction')}: {c['construccio_m2']:>6,} €/m²")
                lines.append(f"    {L('land')}: {c['sol_estimat_m2']:>6,} €/m²")
                lines.append(f"    {L('soft_costs')}: {c['costos_tous_m2']:>6,} €/m²")
                lines.append(f"    {L('total')}: {c['cost_total_m2']:>6,} €/m²")
                lines.append(f"\n  {L('margins')}:")
                lines.append(f"    {L('gross_now')}: {mg['marge_brut_m2']:>6,} €/m² ({mg['marge_brut_pct']})")
                if mg.get("marge_projectat_6m_m2") is not None:
                    lines.append(f"    {L('projected_6m')}: {mg['marge_projectat_6m_m2']:>6,} €/m² "
                                 f"({mg['marge_projectat_6m_pct']})")
                else:
                    lines.append(f"    {L('projected_6m')}: {L('no_trend')}")
            else:
                lines.append(f"  {L('reason')}: {f.get('razon', '')}")
                lines.append(f"  {L('action')}: {f.get('recomendacion', '')}")
            if f.get("riscos"):
                lines.append(f"\n  {L('risks')}:")
                for risk in f["riscos"]:
                    lines.append(f"    {risk['level']} [{risk['type']}] {risk['desc']}")

        # Footer
        lines.append(f"\n{'═' * 70}")
        lines.append(f"  {L('footer_1')}")
        lines.append(f"  {L('footer_2')}")
        sources = [L("src_" + code) if ("src_" + code) in TEXT["ca"] else code for code in t.fuentes]
        lines.append(f"  {L('sources')}: {', '.join(sources) if sources else '—'}")
        lines.append(f"\n  {L('generated_by')} · {r.timestamp}")
        lines.append(f"  https://value.railnexus.io")
        lines.append("=" * 70)

        return "\n".join(lines)


# ═══════════════════════════════════════════════════════════
# 9. MAIN ORCHESTRATOR
# ═══════════════════════════════════════════════════════════

class MarketIntelligence:
    """
    Main orchestrator: runs the full market analysis pipeline.

    Pipeline:
    1. Catastro → parcel data
    2. SIU → land classification
    3. Idealista API → market prices (or INE fallback)
    4. INE → price trends
    5. Projections → 6 and 12 month forecast
    6. Feasibility → development viability
    7. Report → formatted output
    """

    def __init__(self, allow_historical_reference: bool = False):
        """Create the engine; historical values are opt-in and never treated as live."""
        self.allow_historical_reference = allow_historical_reference

    def analyze_by_coordinates(self, lat: float, lon: float,
                                municipio: str = "",
                                radius_m: int = 1000,
                                language: str = "ca") -> str:
        """Full analysis from GPS coordinates."""

        # 1. Catastro (v14: módulo REAL verificado, cookie F5 + parseo bytes;
        #    v19: a loose point that lands on no parcel is snapped to the
        #    nearest CartoCiudad portal within 150 m before giving up)
        if _REAL_MODULE:
            _rp = CatastroReal.full_lookup_resilient(lat, lon)
            parcel = ParcelData(
                ref_catastral=_rp.ref_catastral, direccion=_rp.direccion,
                municipio=_rp.municipio, provincia=_rp.provincia,
                superficie_construida_m2=_rp.superficie_construida_m2,
                coordinates=_rp.coordinates,
                raw_response=(f"resolved_via={_rp.resolved_via}"
                              + (f" snap={_rp.snap_distance_m} m -> {_rp.geocoder_address}"
                                 if _rp.resolved_via == "cartociudad_reverse_snap" else "")
                              + (f" error={_rp.error}" if _rp.error else "")))
            parcel.uso = _rp.uso if hasattr(parcel, 'uso') else _rp.uso
        else:
            parcel = Catastro.by_coordinates(lat, lon)
        if not parcel.municipio and municipio:
            parcel.municipio = municipio

        # 2. Land classification
        land = SIUClassifier.classify(lat, lon, parcel.municipio or municipio)

        # 3. Market prices — live Idealista; historical reference is explicit opt-in
        market = self._get_market_prices(lat, lon, parcel.municipio, radius_m)

        # 4. Price trends from INE
        trend = self._get_trends(parcel.municipio or municipio, market)

        # 5. Feasibility
        feasibility = FeasibilityCalc.calculate(
            land, market, trend, parcel.municipio or municipio, language)

        # 6. Build report
        report = MarketReport(
            parcel=parcel,
            land_class=land,
            market=market,
            trend=trend,
            feasibility=feasibility,
            semaforo=feasibility.get("semaforo", ""),
            recomendacion=feasibility.get("viable", ""),
            timestamp=datetime.now().strftime("%d/%m/%Y %H:%M"),
        )

        return MarketReportGenerator.generate(report, language)

    def analyze_by_address(self, provincia: str, municipio: str,
                           via: str, numero: str,
                           radius_m: int = 1000,
                           language: str = "ca") -> str:
        """Full analysis from street address (v14: geocoding REAL via DNPLOC;
        v19: when Catastro's callejero rejects the street as typed, the address
        is geocoded with CartoCiudad and the parcel looked up at that point)."""
        geocode_note = ""
        if _REAL_MODULE:
            _rp = CatastroReal.locate(provincia=provincia, municipio=municipio,
                                      calle=via, numero=numero)
            if _rp.error or not _rp.ref_catastral:
                geo = CartoCiudadGeocoder.geocode(f"{via} {numero}, {municipio}")
                if geo.ok and geo.parcel_grade:      # portal-level only: never a street centroid
                    alt = (CatastroReal.by_refcat(geo.ref_catastral) if geo.ref_catastral
                           else CatastroReal.full_lookup(geo.lat, geo.lon))
                    if alt.error or not alt.ref_catastral:
                        alt = CatastroReal.full_lookup_resilient(geo.lat, geo.lon)
                    if not alt.error and alt.ref_catastral:
                        alt.coordinates = alt.coordinates if alt.coordinates != (0.0, 0.0) else (geo.lat, geo.lon)
                        alt.resolved_via = "cartociudad_address"
                        geocode_note = (f"Catastro DNPLOC: {_rp.error or 'sin parcela'} -> CartoCiudad "
                                        f"'{geo.address}' ({geo.lat:.5f}, {geo.lon:.5f})")
                        _rp = alt
                    else:
                        geocode_note = (f"Catastro DNPLOC: {_rp.error or 'sin parcela'} | CartoCiudad "
                                        f"'{geo.address}' -> {alt.error or 'sin parcela'}")
                else:
                    geocode_note = (f"Catastro DNPLOC: {_rp.error or 'sin parcela'} | CartoCiudad: "
                                    + (geo.error or f"solo resuelve a nivel {geo.precision or 'sin punto'} "
                                                    f"({geo.type} '{geo.address}'), no a portal"))
            parcel = ParcelData(
                ref_catastral=_rp.ref_catastral, direccion=_rp.direccion,
                municipio=_rp.municipio or municipio,
                provincia=_rp.provincia or provincia,
                superficie_construida_m2=_rp.superficie_construida_m2,
                coordinates=_rp.coordinates,
                raw_response=(f"resolved_via={_rp.resolved_via} {geocode_note}".strip()
                              + (f" error={_rp.error}" if _rp.error else "")))
        else:
            parcel = Catastro.by_address(provincia, municipio, via, numero)

        # If we got coordinates, use them; otherwise the analysis has no point:
        # v19 — NO silent city-centre fallback (it produced a "parcel" that was
        # simply the middle of the city). The zoning step then reports UNKNOWN.
        if parcel.coordinates != (0, 0) and parcel.coordinates != (0.0, 0.0):
            lat, lon = parcel.coordinates
        else:
            lat, lon = (0.0, 0.0)

        parcel.municipio = municipio
        parcel.provincia = provincia

        if (lat, lon) == (0.0, 0.0):
            land = LandClassification(
                observaciones="Sin coordenadas: la dirección no se pudo geolocalizar (Catastro ni "
                              "CartoCiudad); no hay consulta de suelo posible. "
                              + (parcel.raw_response or ""),
                source="SIU (sin datos)", verified_for_parcel=False, verification_status="UNKNOWN")
        else:
            land = SIUClassifier.classify(lat, lon, municipio)
        market = self._get_market_prices(lat, lon, municipio, radius_m)
        trend = self._get_trends(municipio, market)
        feasibility = FeasibilityCalc.calculate(land, market, trend, municipio, language)

        report = MarketReport(
            parcel=parcel, land_class=land, market=market, trend=trend,
            feasibility=feasibility,
            semaforo=feasibility.get("semaforo", ""),
            recomendacion=feasibility.get("viable", ""),
            timestamp=datetime.now().strftime("%d/%m/%Y %H:%M"),
        )
        return MarketReportGenerator.generate(report, language)

    def _get_market_prices(self, lat: float, lon: float,
                           municipio: str, radius_m: int) -> MarketPrice:
        """Get live Idealista prices or an explicitly labelled historical reference."""

        # Try Idealista API first
        nueva = IdealistaAPI.search(lat, lon, radius_m,
                                    build_type="newDevelopment")
        segunda = IdealistaAPI.search(lat, lon, radius_m,
                                      build_type="secondHand")

        if nueva.get("status") == "ok" and segunda.get("status") == "ok":
            p_nueva = nueva["precio_m2_medio"]
            p_segunda = segunda["precio_m2_medio"]
            return MarketPrice(
                precio_m2_nueva=p_nueva,
                precio_m2_segunda=p_segunda,
                precio_m2_promedio=round((p_nueva + p_segunda) / 2),
                num_listings_nueva=nueva["total"],
                num_listings_segunda=segunda["total"],
                tamaño_medio_nueva_m2=nueva["tamaño_medio_m2"],
                tamaño_medio_segunda_m2=segunda["tamaño_medio_m2"],
                ratio_nueva_vs_segunda=round(p_nueva/p_segunda, 2) if p_segunda else 0,
                radio_busqueda_m=radius_m,
                fecha_datos=datetime.now().strftime("%d/%m/%Y"),
                source="Idealista API",
                data_status="LIVE",
            )

        if not self.allow_historical_reference:
            messages = [str(item.get("message") or item.get("code") or item.get("status"))
                        for item in (nueva, segunda) if item.get("status") != "ok"]
            return MarketPrice(
                radio_busqueda_m=radius_m,
                fecha_datos=datetime.now().strftime("%d/%m/%Y"),
                source="NO_LIVE_MARKET_DATA",
                data_status="NO_LIVE_MARKET_DATA",
                source_errors=messages,
            )

        # Explicitly opted-in historical reference data
        muni_lower = municipio.lower().strip()
        for city, data in REFERENCE_MARKET_DATA.items():
            if city in muni_lower:
                return MarketPrice(
                    precio_m2_nueva=data["precio_m2_nueva"],
                    precio_m2_segunda=data["precio_m2_segunda"],
                    precio_m2_promedio=data["precio_m2_promedio"],
                    tamaño_medio_nueva_m2=data["tamaño_medio_nueva"],
                    tamaño_medio_segunda_m2=data["tamaño_medio_segunda"],
                    ratio_nueva_vs_segunda=round(
                        data["precio_m2_nueva"]/data["precio_m2_segunda"], 2),
                    radio_busqueda_m=radius_m,
                    fecha_datos=data["fecha"],
                    source=f"HISTORICAL_REFERENCE ({', '.join(data['fuentes'])})",
                    data_status="HISTORICAL_REFERENCE",
                )

        # Last resort: national average
        return MarketPrice(
            precio_m2_nueva=2200, precio_m2_segunda=1650,
            precio_m2_promedio=1900,
            source="HISTORICAL_REFERENCE — national fallback",
            fecha_datos="Q4 2025",
            data_status="HISTORICAL_REFERENCE",
        )

    @staticmethod
    def ccaa_for_municipio(municipio: str) -> Optional[str]:
        """Map a municipality/province name to the CCAA key used for INE lookups."""
        muni_lower = municipio.lower().strip()
        for prov, cc in PROVINCE_TO_CCAA.items():
            if prov in muni_lower:
                return cc
        return None

    @staticmethod
    def select_ine_variation_series(ipv: Dict, ccaa: str, kind: str = "trimestral") -> List[float]:
        """Return the ``variación {kind}`` values (oldest first) for ``ccaa`` from an
        INE IPV table response (80270; same layout as the legacy 25171), or ``[]``
        when no plausible series exists.

        The table contains, per CCAA and per housing class, sibling series: the
        index level ("Índice"), the quarterly variation, the annual variation and
        the year-to-date variation. v15 picked the first series whose name
        contained the CCAA (the index) and summed four index levels as "annual
        growth". Verified on 80270 (2026-09-16): Madrid annual 12.9 %, national
        12.2 % for 2026 T2.
        """
        series = ipv.get("series") or {}
        label = _normalize(INE_CCAA_LABELS.get(ccaa, ccaa))
        wanted = _normalize(f"variacion {kind}")
        candidates = []
        for name, values in series.items():
            norm = _normalize(name)
            if label not in norm or wanted not in norm:
                continue
            # prefer the "General" series (all dwellings) over nueva/segunda mano
            priority = 0 if "general" in norm else 1
            vals = [float(v["value"]) for v in values if v.get("value") is not None]
            if not vals or any(abs(v) > MAX_PLAUSIBLE_VARIATION_PCT for v in vals):
                continue
            candidates.append((priority, name, vals))
        if not candidates:
            return []
        candidates.sort(key=lambda item: (item[0], item[1]))
        return candidates[0][2][-8:]

    def _get_trends(self, municipio: str, market: MarketPrice) -> PriceTrend:
        """Get price trends from INE; never from a silent default growth rate."""
        muni_lower = municipio.lower().strip()
        ccaa = self.ccaa_for_municipio(municipio)

        quarterly_data: List[float] = []
        annual_growth: Optional[float] = None
        ipv = INEPrices.get_ipv(periods=8)
        if ipv.get("status") == "ok" and ccaa:
            quarterly_data = self.select_ine_variation_series(ipv, ccaa, "trimestral")
            annual_series = self.select_ine_variation_series(ipv, ccaa, "anual")
            if annual_series:
                annual_growth = annual_series[-1]
            elif len(quarterly_data) >= 4:
                # compound the last four quarterly variations
                growth = 1.0
                for q in quarterly_data[-4:]:
                    growth *= 1 + q / 100
                annual_growth = round((growth - 1) * 100, 2)

        if len(quarterly_data) >= 4 and annual_growth is not None:
            trend = PriceProjector.full_projection(market, annual_growth, quarterly_data)
            trend.fuentes = ["ine", "catastro", "siu"]
            return trend

        # Opt-in historical reference trend (explicitly labelled, never current)
        if self.allow_historical_reference:
            for city, data in REFERENCE_MARKET_DATA.items():
                if city in muni_lower:
                    trend = PriceProjector.full_projection(market, data["variacion_anual_pct"], None)
                    trend.metodo = "historical_reference_trend"
                    trend.confianza = "low"
                    trend.fuentes = ["reference", "catastro", "siu"]
                    return trend

        # No usable series: say so. v15 silently used annual_growth = 10.0.
        return PriceTrend(
            variacion_trimestral=[], variacion_anual_pct=0, tendencia="",
            proyeccion_6_meses_nueva=0, proyeccion_6_meses_segunda=0,
            proyeccion_12_meses_nueva=0, confianza="none", metodo="no_trend_data",
            fuentes=["catastro", "siu"],
        )

    @staticmethod
    def _city_center(municipio: str) -> Tuple[float, float]:
        """Get approximate city center coordinates."""
        centers = {
            "valencia": (39.4699, -0.3763),
            "barcelona": (41.3874, 2.1686),
            "madrid": (40.4168, -3.7038),
            "sevilla": (37.3891, -5.9845),
            "malaga": (36.7213, -4.4214),
            "bilbao": (43.2630, -2.9350),
            "zaragoza": (41.6488, -0.8891),
        }
        muni = municipio.lower().strip()
        for city, coords in centers.items():
            if city in muni:
                return coords
        return (40.4168, -3.7038)  # Madrid default


# ═══════════════════════════════════════════════════════════
# CLI ENTRY POINT
# ═══════════════════════════════════════════════════════════

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description="RailNexus Market Intelligence")
    parser.add_argument("--lat", type=float, help="Latitude")
    parser.add_argument("--lon", type=float, help="Longitude")
    parser.add_argument("--city", default="", help="City name")
    parser.add_argument("--address", default="", help="Street address")
    parser.add_argument("--province", default="", help="Province for address lookup")
    parser.add_argument("--number", default="", help="Street number; may be included in --address")
    parser.add_argument("--radius", type=int, default=1000,
                        help="Search radius in meters")
    parser.add_argument("--lang", default="ca", choices=list(SUPPORTED_LANGUAGES),
                        help="Report language; every string (headers, feasibility, risks, "
                             "methods) is localised — default ca")
    parser.add_argument("--allow-historical-reference", action="store_true",
                        help="Show dated embedded values as historical context only")

    args = parser.parse_args()

    engine = MarketIntelligence(
        allow_historical_reference=args.allow_historical_reference)

    if (args.lat is None) != (args.lon is None):
        parser.error("--lat and --lon must be supplied together")

    if args.lat is not None and args.lon is not None:
        result = engine.analyze_by_coordinates(
            args.lat, args.lon, args.city, args.radius, args.lang)
    elif args.address:
        if not args.city:
            parser.error("--city is required with --address")
        street = args.address.strip()
        number = args.number.strip()
        if not number:
            match = re.match(r"^(.*?)[, ]+(\d+[A-Za-z]?)$", street)
            if not match:
                parser.error("include a street number in --address or pass --number")
            street, number = match.group(1).strip(), match.group(2)
        result = engine.analyze_by_address(
            args.province or args.city, args.city, street, number,
            args.radius, args.lang)
    elif args.city:
        coords = engine._city_center(args.city)
        result = engine.analyze_by_coordinates(
            coords[0], coords[1], args.city, args.radius, args.lang)
    else:
        parser.error("supply --lat/--lon, --city, or --address with --city")

    print(result)