File size: 51,859 Bytes
e6c137b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import Dict, List, Optional, Any
import requests
from bs4 import BeautifulSoup
import re
import time
import logging
from urllib.parse import urlparse
from datetime import datetime
import uvicorn
import os

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# FastAPI app initialization
app = FastAPI(
    title="Caltrans Payment Tracking System",
    description="API for retrieving contract payment history and detailed monthly estimates",
    version="1.0.0"
)

# Pydantic Models
class PaymentRecord(BaseModel):
    estimate_number: str = Field(..., description="Estimate number")
    detail_link: Optional[str] = Field(None, description="Link to payment details")
    voucher_link: Optional[str] = Field(None, description="Link to voucher")
    type: str = Field(..., description="Payment type")
    payment_type: str = Field(..., description="Payment classification")
    release_date: str = Field(..., description="Payment release date")
    held_amount: float = Field(..., description="Amount held")
    disbursed_amount: float = Field(..., description="Amount disbursed")

class ContractDetails(BaseModel):
    contract_number: str = Field(..., description="Contract number")
    contractor_name: Optional[str] = Field(None, description="Contractor name")
    last_updated: Optional[str] = Field(None, description="Last update date")
    job_description: Optional[str] = Field(None, description="Job description")
    contract_accepted: Optional[str] = Field(None, description="Contract acceptance date")
    stop_notice_deadline: Optional[str] = Field(None, description="Stop notice deadline")
    suit_filing_expiration: Optional[str] = Field(None, description="Suit filing expiration")
    estimated_completion: Optional[str] = Field(None, description="Estimated completion date")
    current_withhold: Optional[float] = Field(None, description="Current withhold amount")
    currently_held: Optional[float] = Field(None, description="Currently held amount")
    need_to_hold: Optional[float] = Field(None, description="Amount needed to hold")

class ContactInfo(BaseModel):
    email: Optional[str] = Field(None, description="Contact email")
    phone: Optional[str] = Field(None, description="Contact phone")

class PaymentSummary(BaseModel):
    total_payments: int = Field(..., description="Total number of payments")
    total_disbursed: float = Field(..., description="Total amount disbursed")
    total_held: float = Field(..., description="Total amount held")
    latest_payment_date: str = Field(..., description="Date of latest payment")


class Quantities(BaseModel):
    original: float = Field(..., description="Original quantity")
    this_period: float = Field(..., description="This period quantity")
    percent_this_period: float = Field(..., description="Percentage this period")
    job_to_date: float = Field(..., description="Job to date quantity")
    percent_jtd: float = Field(..., description="Percentage job to date")

class Amounts(BaseModel):
    original: float = Field(..., description="Original amount")
    this_period: float = Field(..., description="This period amount")
    job_to_date: float = Field(..., description="Job to date amount")
    moh: float = Field(..., description="Materials on hand")

class LineItem(BaseModel):
    item_number: str = Field(..., description="Item number")
    revenue_code: str = Field(..., description="Revenue code")
    description: str = Field(..., description="Work description")
    sub_item: str = Field(..., description="Y=Subcontracted, N=Self-performed")
    quantities: Quantities
    units: str = Field(..., description="Unit of measurement")
    unit_price: float = Field(..., description="Unit price")
    amounts: Amounts

class DetailedPaymentRecord(BaseModel):
    estimate_number: str = Field(..., description="Estimate number")
    detail_link: Optional[str] = Field(None, description="Link to payment details")
    voucher_link: Optional[str] = Field(None, description="Link to voucher")
    type: str = Field(..., description="Payment type")
    payment_type: str = Field(..., description="Payment classification")
    release_date: str = Field(..., description="Payment release date")
    held_amount: float = Field(..., description="Amount held")
    disbursed_amount: float = Field(..., description="Amount disbursed")
    detailed_estimate: Optional[Dict[str, Any]] = Field(None, description="Detailed CAS145 estimate data")

class MonthlyPaymentSummary(BaseModel):
    month: str = Field(..., description="Month in YYYY-MM format")
    payment_count: int = Field(..., description="Number of payments in month")
    total_disbursed: float = Field(..., description="Total disbursed in month")
    total_held: float = Field(..., description="Total held in month")
    payments: List[DetailedPaymentRecord] = Field(..., description="Individual payments with detailed estimates")

class ContractResponse(BaseModel):
    contract_details: ContractDetails
    payment_history: List[PaymentRecord]
    contact_info: ContactInfo
    summary: PaymentSummary
    monthly_breakdown: Dict[str, float] = Field(..., description="Monthly disbursement breakdown")
    scraped_at: str = Field(..., description="Timestamp when data was scraped")


class CaltransPETSScraper:
    """
    Powerful web scraper for California Department of Transportation (Caltrans) 
    Payment Estimation Tracking System (PETS)
    """
    
    def __init__(self, base_url: str = "https://misc-external.dot.ca.gov/pets/", 
                 delay: float = 1.0, timeout: int = 30):
        """
        Initialize the scraper
        
        Args:
            base_url: Base URL for the PETS system
            delay: Delay between requests (seconds)
            timeout: Request timeout (seconds)
        """
        self.base_url = base_url
        self.delay = delay
        self.timeout = timeout
        self.session = requests.Session()
        
        # Set up headers to mimic a real browser
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
        })
        
        # Set up logging
        self.logger = logging.getLogger(__name__)
        
    def _make_request(self, url: str, method: str = 'GET', **kwargs) -> Optional[requests.Response]:
        """Make a safe HTTP request with error handling"""
        try:
            self.logger.info(f"Making {method} request to: {url}")
            
            if method.upper() == 'GET':
                response = self.session.get(url, timeout=self.timeout, **kwargs)
            else:
                response = self.session.post(url, timeout=self.timeout, **kwargs)
                
            response.raise_for_status()
            time.sleep(self.delay)  # Respect server
            return response
            
        except requests.exceptions.RequestException as e:
            self.logger.error(f"Request failed for {url}: {str(e)}")
            return None
    
    def extract_contract_details(self, soup: BeautifulSoup) -> Dict[str, any]:
        """Extract contract details from a contract page"""
        contract_info = {}
        
        try:
            # Extract contract number and contractor name from header
            header = soup.find('h1', class_='rpt77tx')
            if header:
                header_text = header.get_text(strip=True)
                # Extract contract number (format: 033F0704)
                contract_match = re.search(r'Contract:\s*(\w+)', header_text)
                if contract_match:
                    contract_info['contract_number'] = contract_match.group(1)
                
                # Extract contractor name
                lines = header_text.split('\n')
                if len(lines) > 1:
                    contract_info['contractor_name'] = lines[1].strip()
            
            # Extract date last updated
            date_elem = soup.find('div', class_='rpt77b')
            if date_elem and 'Date last updated:' in date_elem.get_text():
                date_text = date_elem.get_text(strip=True)
                date_match = re.search(r'Date last updated:\s*(\d{2}/\d{2}/\d{2})', date_text)
                if date_match:
                    contract_info['last_updated'] = date_match.group(1)
            
            # Extract contract details from the list
            details_list = soup.find('ul', class_='rpt77')
            if details_list:
                for li in details_list.find_all('li'):
                    text = li.get_text(strip=True)
                    
                    if 'Job Description:' in text:
                        # Extract job description from blockquote
                        blockquote = li.find('blockquote')
                        if blockquote:
                            contract_info['job_description'] = blockquote.get_text(strip=True)
                    elif 'Contract Accepted:' in text:
                        contract_info['contract_accepted'] = text.split(':', 1)[1].strip()
                    elif 'Stop Notice filing deadline:' in text:
                        contract_info['stop_notice_deadline'] = text.split(':', 1)[1].strip()
                    elif 'Expiration of Suit-filing period:' in text:
                        contract_info['suit_filing_expiration'] = text.split(':', 1)[1].strip()
                    elif 'Estimated Completion:' in text:
                        completion_text = text.split(':', 1)[1].strip()
                        contract_info['estimated_completion'] = completion_text
                    elif 'Current Withhold Obligations:' in text:
                        amount = re.search(r'\$([0-9,]+\.\d{2})', text)
                        if amount:
                            contract_info['current_withhold'] = float(amount.group(1).replace(',', ''))
                    elif 'Curently Held:' in text:  # Note: typo in original
                        amount = re.search(r'\$([0-9,]+\.\d{2})', text)
                        if amount:
                            contract_info['currently_held'] = float(amount.group(1).replace(',', ''))
                    elif 'Need to Hold:' in text:
                        amount = re.search(r'\$([0-9,]+\.\d{2})', text)
                        if amount:
                            contract_info['need_to_hold'] = float(amount.group(1).replace(',', ''))
            
            return contract_info
            
        except Exception as e:
            self.logger.error(f"Error extracting contract details: {str(e)}")
            return contract_info
    
    def extract_payment_history(self, soup: BeautifulSoup) -> List[Dict[str, any]]:
        """Extract payment history from the payment table"""
        payments = []
        
        try:
            # Find the payment history table
            payment_table = soup.find('table', class_='reporttablelft2')
            if not payment_table:
                self.logger.warning("Payment table not found")
                return payments
            
            # Find all data rows (skip header)
            rows = payment_table.find_all('tr')[1:]  # Skip header row
            
            for row in rows:
                cells = row.find_all('td')
                if len(cells) >= 8:  # Ensure we have enough columns
                    
                    # Skip total row
                    if 'Total:' in cells[0].get_text(strip=True):
                        continue
                    
                    payment = {}
                    
                    # Extract estimate number
                    payment['estimate_number'] = cells[0].get_text(strip=True)
                    
                    # Extract detail and voucher links (IMPORTANT!)
                    detail_link = cells[1].find('a')
                    if detail_link:
                        payment['detail_link'] = detail_link.get('href')
                    
                    voucher_link = cells[2].find('a')
                    if voucher_link:
                        payment['voucher_link'] = voucher_link.get('href')
                    
                    # Extract type
                    payment['type'] = cells[3].get_text(strip=True)
                    
                    # Extract payment type
                    payment['payment_type'] = cells[4].get_text(strip=True)
                    
                    # Extract release date
                    payment['release_date'] = cells[5].get_text(strip=True)
                    
                    # Extract held amount
                    held_text = cells[6].get_text(strip=True).replace('$', '').replace(',', '')
                    try:
                        payment['held_amount'] = float(held_text) if held_text else 0.0
                    except ValueError:
                        payment['held_amount'] = 0.0
                    
                    # Extract disbursed amount
                    disbursed_text = cells[7].get_text(strip=True).replace('$', '').replace(',', '')
                    try:
                        payment['disbursed_amount'] = float(disbursed_text) if disbursed_text else 0.0
                    except ValueError:
                        payment['disbursed_amount'] = 0.0
                    
                    payments.append(payment)
            
            return payments
            
        except Exception as e:
            self.logger.error(f"Error extracting payment history: {str(e)}")
            return payments
    
    def extract_contact_info(self, soup: BeautifulSoup) -> Dict[str, str]:
        """Extract contact information for payment inquiries"""
        contact_info = {}
        
        try:
            # Look for contact information
            contact_section = soup.find(text="Please direct Payment Inquiries to:")
            if contact_section:
                parent = contact_section.parent
                if parent:
                    # Extract email
                    email_link = parent.find('a', href=re.compile(r'mailto:'))
                    if email_link:
                        contact_info['email'] = email_link.get('href').replace('mailto:', '').split('?')[0]
                    
                    # Extract phone
                    phone_match = re.search(r'Phone:\s*\((\d{3})\)\s*(\d{3}-\d{4})', parent.get_text())
                    if phone_match:
                        contact_info['phone'] = f"({phone_match.group(1)}) {phone_match.group(2)}"
            
            return contact_info
            
        except Exception as e:
            self.logger.error(f"Error extracting contact info: {str(e)}")
            return contact_info
    
    def parse_payment_date(self, date_str: str) -> datetime:
        """
        Intelligently parse payment dates handling both 2-digit and 4-digit years
        
        Args:
            date_str: Date string in format "MM/DD/YY" or "MM/DD/YYYY"
            
        Returns:
            datetime object with correct year
            
        Note:
            For 2-digit years, assumes years 00-29 are 2000-2029 and years 30-99 are 1930-1999
            This follows the "sliding window" approach used by many systems
        """
        try:
            # First try 4-digit year format
            return datetime.strptime(date_str, '%m/%d/%Y')
        except ValueError:
            # If that fails, try 2-digit year format
            try:
                date_obj = datetime.strptime(date_str, '%m/%d/%y')
                
                # Apply sliding window logic for 2-digit years
                # Years 00-29 are interpreted as 2000-2029
                # Years 30-99 are interpreted as 1930-1999
                if date_obj.year < 2000:
                    # If year is less than 2000, it's likely from the 2000s
                    # Adjust based on current year context
                    current_year = datetime.now().year
                    if current_year >= 2020:
                        # We're in 2020s, so adjust accordingly
                        if date_obj.year < 30:  # 00-29
                            date_obj = date_obj.replace(year=date_obj.year + 2000)
                        else:  # 30-99
                            date_obj = date_obj.replace(year=date_obj.year + 1900)
                    else:
                        # We're in earlier years, use standard sliding window
                        if date_obj.year < 50:  # 00-49
                            date_obj = date_obj.replace(year=date_obj.year + 2000)
                        else:  # 50-99
                            date_obj = date_obj.replace(year=date_obj.year + 1900)
                
                return date_obj
                
            except ValueError:
                raise ValueError(f"Unable to parse date: {date_str}. Expected format: MM/DD/YY or MM/DD/YYYY")
    
    def scrape_contract(self, contract_number: str) -> Dict[str, any]:
        """Scrape complete contract information from a contract number"""
        contract_url = f"{self.base_url}results.php?ctrnm={contract_number}"
        
        response = self._make_request(contract_url)
        if not response:
            return {}
        
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Extract all information
        contract_data = {
            'url': contract_url,
            'scraped_at': datetime.now().isoformat(),
            'contract_details': self.extract_contract_details(soup),
            'payment_history': self.extract_payment_history(soup),
            'contact_info': self.extract_contact_info(soup)
        }
        
        # Calculate summary statistics
        if contract_data['payment_history']:
            total_disbursed = sum(p['disbursed_amount'] for p in contract_data['payment_history'])
            total_held = sum(p['held_amount'] for p in contract_data['payment_history'])
            
            contract_data['summary'] = {
                'total_payments': len(contract_data['payment_history']),
                'total_disbursed': total_disbursed,
                'total_held': total_held,
                'latest_payment_date': max((p['release_date'] for p in contract_data['payment_history'] if p['release_date']), default='N/A')
            }
            
            # Calculate monthly breakdown
            monthly_breakdown = {}
            for payment in contract_data['payment_history']:
                if payment['release_date'] and payment['release_date'] != 'N/A':
                    try:
                        # Parse date and extract month - handle both 2-digit and 4-digit years intelligently
                        date_obj = self.parse_payment_date(payment['release_date'])
                        
                        month_key = date_obj.strftime('%Y-%m')
                        
                        if month_key not in monthly_breakdown:
                            monthly_breakdown[month_key] = 0.0
                        monthly_breakdown[month_key] += payment['disbursed_amount']
                    except ValueError:
                        continue
            
            contract_data['monthly_breakdown'] = monthly_breakdown
        
        return contract_data


class CAS145Parser:
    """
    Parser for California DOT CAS145 Progress Estimate Reports
    
    Converts CAS145 text format to GC Pay JSON format with proper calculations
    """
    
    def __init__(self):
        self.data = {
            "prime_contract": {"items": [], "total": {}},
            "change_orders": {"items": [], "total": {}},
            "deductions": [],
            "extra_work_totals": {
                'total_this_estimate': 0.0,
                'total_previous_estimate': 0.0,
                'total_to_date': 0.0
            }
        }
        self.main_estimate_no = None
        
    def fetch_from_url(self, url: str) -> str:
        """Fetch content from URL"""
        try:
            response = requests.get(url, timeout=30)
            response.raise_for_status()
            return response.text
        except requests.RequestException as e:
            raise Exception(f"Failed to fetch URL: {e}")
    
    def parse_content(self, content: str) -> Dict:
        """Parse CAS145 content"""
        sections = self.split_sections(content)
        
        self.parse_extra_work(sections.get('extra_work', ''))
        self.parse_deductions(sections.get('deductions', ''))
        self.parse_project_items(sections.get('items', ''))
        
        self.calculate_totals()
        
        return self.data
    
    def split_sections(self, content: str) -> Dict[str, str]:
        """Split content into major sections"""
        sections = {}
        
        # Find section boundaries
        extra_work_start = content.find('S C H E D U L E   O F   E X T R A   W O R K')
        deductions_start = content.find('S C H E D U L E   O F   D E D U C T I O N S')
        items_start = content.find('P R O J E C T   R E C O R D  -  E S T I M A T E')
        
        # Extract sections
        if extra_work_start > 0 and deductions_start > 0:
            sections['extra_work'] = content[extra_work_start:deductions_start]
        
        if deductions_start > 0 and items_start > 0:
            sections['deductions'] = content[deductions_start:items_start]
        
        if items_start > 0:
            items_content = content[items_start:]
            sections['items'] = items_content
        
        return sections
    
    def set_estimate_number(self, estimate_no: str):
        """Set estimate number from URL filename"""
        self.main_estimate_no = estimate_no
    
    def parse_extra_work(self, section: str):
        """Parse Schedule of Extra Work section with improved flexibility for various formats"""
        if not section:
            return
            
        lines = section.split('\n')
        parsed_count = 0
        
        # Initialize totals tracking
        self.data['extra_work_totals'] = {
            'total_this_estimate': 0.0,
            'total_previous_estimate': 0.0,
            'total_to_date': 0.0
        }
        
        logger.info(f"Parsing extra work section with {len(lines)} lines")
        
        for i, line in enumerate(lines):
            # Skip empty lines
            if not line.strip():
                continue
            
            # Extract totals for reference (but don't parse as line items)
            line_lower = line.lower()
            if 'total this estimate' in line_lower:
                amount_match = re.search(r'([\d,]+\.\d{2})', line)
                if amount_match:
                    self.data['extra_work_totals']['total_this_estimate'] = self.parse_currency(amount_match.group(1))
                logger.debug(f"Extracted total this estimate: {self.data['extra_work_totals']['total_this_estimate']}")
                continue
            elif 'total previous estimate' in line_lower:
                amount_match = re.search(r'([\d,]+\.\d{2})', line)
                if amount_match:
                    self.data['extra_work_totals']['total_previous_estimate'] = self.parse_currency(amount_match.group(1))
                logger.debug(f"Extracted total previous estimate: {self.data['extra_work_totals']['total_previous_estimate']}")
                continue
            elif 'total to date' in line_lower:
                amount_match = re.search(r'([\d,]+\.\d{2})', line)
                if amount_match:
                    self.data['extra_work_totals']['total_to_date'] = self.parse_currency(amount_match.group(1))
                logger.debug(f"Extracted total to date: {self.data['extra_work_totals']['total_to_date']}")
                continue
            
            # Skip other total and summary lines
            if any(total_indicator in line_lower for total_indicator in [
                'total:',
                'total ',
                'subtotal',
                'grand total'
            ]):
                logger.debug(f"Skipping total line {i+1}: {line.strip()}")
                continue
                
            logger.debug(f"Processing line {i+1}: {line.strip()}")
                
            # Try to parse the line using our helper method
            parsed_item = self.parse_extra_work_line(line)
            if parsed_item:
                self.data['change_orders']['items'].append(parsed_item)
                parsed_count += 1
                logger.debug(f"Successfully parsed line {i+1} as {parsed_item['change_order_no']}: {parsed_item['description']}")
                continue
            
            # If the helper method didn't parse it, try some additional fallback patterns
            # Look for lines that might contain extra work information but don't fit standard patterns
            
            # Pattern: Lines with amounts and dates that might be extra work
            amount_date_match = re.search(r'([\d,]+\.\d{2})\s+(\d{2}/\d{2}/\d{2})', line)
            if amount_date_match and ('E.W.' in line or 'EXTRA' in line.upper()):
                amount = self.parse_currency(amount_date_match.group(1))
                date = amount_date_match.group(2)
                
                # Extract any other meaningful information
                identifier = self.extract_identifier_from_line(line)
                
                cco_item = {
                    "change_order_no": "EW_DATE",
                    "revenue_code": "",
                    "description": f"Extra Work by Date: {date} - {identifier}",
                    "sub_item": "",
                    "original_qty": 0,
                    "this_period_qty": 0,
                    "job_to_date_qty": 0,
                    "units": "LS",
                    "unit_price": amount,
                    "original_amt": 0,
                    "this_period_amt": amount,
                    "job_to_date_amt": amount
                }
                self.data['change_orders']['items'].append(cco_item)
                parsed_count += 1
                logger.debug(f"Parsed line {i+1} as EW_DATE: {cco_item['description']}")
                continue
            
            # Pattern: Lines that just have amounts and might be extra work
            # This is a very permissive fallback for lines that contain amounts
            if 'E.W.' in line or 'EXTRA' in line.upper():
                amount_match = re.search(r'([\d,]+\.\d{2})', line)
                if amount_match:
                    amount = self.parse_currency(amount_match.group(1))
                    identifier = self.extract_identifier_from_line(line)
                    
                    cco_item = {
                        "change_order_no": "EW_FALLBACK",
                        "revenue_code": "",
                        "description": f"Extra Work (Fallback): {identifier}",
                        "sub_item": "",
                        "original_qty": 0,
                        "this_period_qty": 0,
                        "job_to_date_qty": 0,
                        "units": "LS",
                        "unit_price": amount,
                        "original_amt": 0,
                        "this_period_amt": amount,
                        "job_to_date_amt": amount
                    }
                    self.data['change_orders']['items'].append(cco_item)
                    parsed_count += 1
                    logger.debug(f"Parsed line {i+1} as EW_FALLBACK: {cco_item['description']}")
                    continue
        
        logger.info(f"Successfully parsed {parsed_count} extra work items out of {len(lines)} lines")
        logger.info(f"Extra work totals: This estimate: {self.data['extra_work_totals']['total_this_estimate']}, "
                   f"Previous: {self.data['extra_work_totals']['total_previous_estimate']}, "
                   f"To date: {self.data['extra_work_totals']['total_to_date']}")

    def parse_extra_work_line(self, line: str) -> Optional[Dict]:
        """
        Helper method to parse individual extra work lines with various formats
        
        Args:
            line: The line to parse
            
        Returns:
            Parsed change order item or None if not a valid extra work line
        """
        line = line.strip()
        if not line:
            return None
            
        logger.debug(f"Attempting to parse line: {line}")
            
        # Try different patterns to extract information
        patterns = [
            # Pattern 1: Standard CCO format
            (r'(\d{3})\s+(\d{4})\s+([\d,]+\.\d{2})\s+E\.W\.\s+@\s+F\.A\.', 'CCO'),
            # Pattern 2: Continuation line
            (r'^\s+(\d{4})\s+([\d,]+\.\d{2})', 'CONT'),
            # Pattern 3: Extra work with amount
            (r'([\d,]+\.\d{2})\s+E\.W\.', 'EW'),
            # Pattern 4: Generic amount line
            (r'([\d,]+\.\d{2})', 'GENERIC')
        ]
        
        for pattern, cco_type in patterns:
            match = re.search(pattern, line)
            if match:
                logger.debug(f"Matched pattern {cco_type} for line: {line}")
                if cco_type == 'CCO':
                    amount = self.parse_currency(match.group(3))
                    return {
                        "change_order_no": f"{match.group(2)[0]}",
                        "revenue_code": "",
                        "description": f"CCO {match.group(1)}-{match.group(2)}: E.W. @",
                        "sub_item": "",
                        "original_qty": 0,
                        "this_period_qty": 0,
                        "job_to_date_qty": 0,
                        "units": "LS",
                        "unit_price": amount,
                        "original_amt": 0,
                        "this_period_amt": amount,
                        "job_to_date_amt": amount
                    }
                elif cco_type == 'CONT':
                    amount = self.parse_currency(match.group(2))
                    return {
                        "change_order_no": "CONT",
                        "revenue_code": "",
                        "description": f"Extra Work Continuation: {match.group(1)}",
                        "sub_item": "",
                        "original_qty": 0,
                        "this_period_qty": 0,
                        "job_to_date_qty": 0,
                        "units": "LS",
                        "unit_price": amount,
                        "original_amt": 0,
                        "this_period_amt": amount,
                        "job_to_date_amt": amount
                    }
                elif cco_type in ['EW', 'GENERIC']:
                    amount = self.parse_currency(match.group(1))
                    # Extract identifier
                    identifier = self.extract_identifier_from_line(line)
                    return {
                        "change_order_no": cco_type,
                        "revenue_code": "",
                        "description": f"Extra Work: {identifier}",
                        "sub_item": "",
                        "original_qty": 0,
                        "this_period_qty": 0,
                        "job_to_date_qty": 0,
                        "units": "LS",
                        "unit_price": amount,
                        "original_amt": 0,
                        "this_period_amt": amount,
                        "job_to_date_amt": amount
                    }
        
        logger.debug(f"No patterns matched for line: {line}")
        return None

    def extract_identifier_from_line(self, line: str) -> str:
        """
        Extract meaningful identifier from a line
        
        Args:
            line: The line to extract identifier from
            
        Returns:
            Extracted identifier or "Unknown"
        """
        line_parts = line.strip().split()
        
        for part in line_parts:
            # Look for 4-digit numbers (likely dates or report numbers)
            if re.match(r'^\d{4}$', part):
                return part
            # Look for 3-digit numbers (likely CCO numbers)
            elif re.match(r'^\d{3}$', part):
                return part
            # Look for alphanumeric codes
            elif re.match(r'^[A-Z0-9]+$', part):
                return part
        
        return "Unknown"
    
    def parse_deductions(self, section: str):
        """Parse Schedule of Deductions section"""
        if not section:
            return
            
        lines = section.split('\n')
        current_category = ""
        deductions_list = []
        
        for line in lines:
            # Identify category
            if 'ADMINISTRATIVE' in line:
                current_category = "Administrative"
            elif 'LABOR COMPLIANCE' in line:
                current_category = "Labor Compliance"
            elif 'LIQUIDATED DAMAGES' in line:
                current_category = "Liquidated Damages"
            elif 'OVERBID ITEMS' in line:
                current_category = "Overbid Items"
            
            # Skip total lines
            if 'TOTAL DEDUCTIONS' in line:
                break
            
            # Parse deduction lines
            if current_category and re.search(r'[-\d,]+\.\d{2}', line):
                # Pattern to match deduction lines
                pattern = r'([A-Z][A-Z0-9\s/\-\.]+?)\s+([-\d,]+\.\d{2})\s+(\d{3})'
                match = re.search(pattern, line)
                
                if match:
                    description = match.group(1).strip()
                    amount = self.parse_currency(match.group(2))
                    est_no = match.group(3)
                    
                    deduction = {
                        "estimate_no": est_no,
                        "revenue_code": "",
                        "description": f"{current_category}: {description}",
                        "original": 0,
                        "this_period": amount,
                        "job_to_date": amount
                    }
                    deductions_list.append(deduction)
        
        self.data['deductions'] = [d for d in deductions_list if 'TOTAL DEDUCTIONS' not in d['description']]
    
    def parse_project_items(self, section: str):
        """Parse Project Record items table"""
        if not section:
            return
            
        lines = section.split('\n')
        current_item = None
        items = []
        
        for i, line in enumerate(lines):
            # Skip header lines
            if 'ITEM' in line and 'DESCRIPTION' in line:
                continue
            if '---' in line:
                continue
            if not line.strip():
                continue
            
            # Check if line starts with item number (3 digits)
            if re.match(r'^\d{3}\s', line):
                # Save previous item if exists
                if current_item:
                    items.append(current_item)
                
                # Start new item
                current_item = self.parse_item_line(line)
            
            # Check for (F) marker on current or next line
            elif current_item:
                if '(F)' in line and len(line) < 10:
                    current_item['sub_item'] = 'Y'
        
        # Add last item
        if current_item:
            items.append(current_item)
        
        self.data['prime_contract']['items'] = items
    
    def parse_item_line(self, line: str) -> Dict:
        """Parse a single item line from the project record"""
        item = {
            "item_number": "",
            "revenue_code": "",
            "description": "",
            "sub_item": "N",
            "quantities": {
                "original": 0.0,
                "this_period": 0.0,
                "percent_this_period": 0.0,
                "job_to_date": 0.0,
                "percent_jtd": 0.0
            },
            "units": "",
            "unit_price": 0.0,
            "amounts": {
                "original": 0.0,
                "this_period": 0.0,
                "job_to_date": 0.0,
                "moh": 0.0
            }
        }
        
        # Parse by column positions (approximate)
        try:
            # Item number
            item['item_number'] = line[:3].strip().zfill(3)
            
            # Description
            desc_end = 45
            for unit in ['LS', 'EA', 'LF', 'SF', 'SY', 'CY', 'TON', 'TN', 'LB', 'HR', 'SQFT', 'SQYD', 'CF', 'ACRE']:
                unit_pos = line[40:52].find(unit)
                if unit_pos > -1:
                    desc_end = 40 + unit_pos
                    break
            
            description = line[4:desc_end].strip()
            
            # Check for (F) marker - indicates subcontracted work
            if '(F)' in description:
                item['sub_item'] = 'Y'
                description = description.replace('(F)', '').strip()
            elif '(F)' in line:
                item['sub_item'] = 'Y'
            
            item['description'] = description
            
            # Find unit and parse numeric values
            remaining = line[desc_end:].strip()
            parts = remaining.split()
            
            if parts:
                # Unit
                item['units'] = parts[0] if parts[0] in ['LS', 'EA', 'LF', 'SF', 'SY', 'CY', 'TON', 'TN', 'LB', 'HR', 'SQFT', 'SQYD', 'CF', 'ACRE'] else ''
                
                # Parse numeric values
                nums = []
                for part in parts[1:]:
                    if re.match(r'^[\d,.-]+\.?\d*$', part):
                        nums.append(self.parse_number(part))
                
                # Assign values based on position
                if len(nums) > 0:
                    item['unit_price'] = nums[0]
                if len(nums) > 1:
                    item['amounts']['original'] = nums[1]
                    # For LS items, original quantity is typically 1
                    if item['units'] == 'LS':
                        item['quantities']['original'] = 1.0
                    else:
                        # Back-calculate original quantity from amount and unit price
                        if item['unit_price'] > 0:
                            item['quantities']['original'] = item['amounts']['original'] / item['unit_price']
                
                if len(nums) > 2:
                    item['quantities']['this_period'] = nums[2]
                if len(nums) > 3:
                    item['amounts']['this_period'] = nums[3]
                if len(nums) > 4:
                    item['quantities']['job_to_date'] = nums[4]
                if len(nums) > 5:
                    item['amounts']['job_to_date'] = nums[5]
            
            # Calculate percentages
            if item['quantities']['original'] > 0:
                if item['quantities']['this_period'] > 0:
                    item['quantities']['percent_this_period'] = round(
                        (item['quantities']['this_period'] / item['quantities']['original']) * 100, 2
                    )
                if item['quantities']['job_to_date'] > 0:
                    item['quantities']['percent_jtd'] = round(
                        (item['quantities']['job_to_date'] / item['quantities']['original']) * 100, 2
                    )
        
        except Exception as e:
            # Return item with defaults if parsing fails
            pass
        
        return item
    
    def parse_currency(self, value_str: str) -> float:
        """Parse currency string to float"""
        if not value_str:
            return 0.0
        try:
            clean = value_str.replace(',', '').replace('$', '').strip()
            if clean.startswith('(') and clean.endswith(')'):
                clean = '-' + clean[1:-1]
            return float(clean)
        except:
            return 0.0
    
    def parse_number(self, value_str: str) -> float:
        """Parse numeric string to float"""
        if not value_str:
            return 0.0
        try:
            clean = value_str.replace(',', '').strip()
            return float(clean)
        except:
            return 0.0
    
    def calculate_totals(self):
        """Calculate all totals from the parsed items"""
        # Prime contract totals
        prime_total = {
            "original": sum(item['amounts']['original'] for item in self.data['prime_contract']['items']),
            "this_period": sum(item['amounts']['this_period'] for item in self.data['prime_contract']['items']),
            "job_to_date": sum(item['amounts']['job_to_date'] for item in self.data['prime_contract']['items']),
            "moh": 0.0
        }
        
        self.data['prime_contract']['total'] = prime_total
        
        # Change order totals
        co_total = {
            "original": 0,
            "this_period": sum(item['this_period_amt'] for item in self.data['change_orders']['items']),
            "job_to_date": sum(item['job_to_date_amt'] for item in self.data['change_orders']['items'])
        }
        
        self.data['change_orders']['total'] = co_total
        
        # Calculate overall project totals including extra work
        overall_total = {
            "original": prime_total["original"],
            "this_period": prime_total["this_period"] + co_total["this_period"],
            "job_to_date": prime_total["job_to_date"] + co_total["job_to_date"],
            "extra_work_this_estimate": self.data.get('extra_work_totals', {}).get('total_this_estimate', 0.0),
            "extra_work_previous": self.data.get('extra_work_totals', {}).get('total_previous_estimate', 0.0),
            "extra_work_to_date": self.data.get('extra_work_totals', {}).get('total_to_date', 0.0)
        }
        
        self.data['overall_totals'] = overall_total
        
        # Store estimate number in data
        self.data['main_estimate_no'] = self.main_estimate_no
        
        # Log summary information
        logger.info(f"Calculated totals for estimate {self.main_estimate_no}:")
        logger.info(f"  Prime contract: ${overall_total['original']:,.2f} original, ${overall_total['job_to_date']:,.2f} to date")
        logger.info(f"  Change orders: ${co_total['this_period']:,.2f} this period, ${co_total['job_to_date']:,.2f} to date")
        logger.info(f"  Extra work: ${overall_total['extra_work_this_estimate']:,.2f} this estimate, ${overall_total['extra_work_to_date']:,.2f} to date")
        logger.info(f"  Overall: ${overall_total['job_to_date']:,.2f} total to date")

    def parse_from_url(self, url: str) -> Dict:
        """Parse a CAS145 file from URL"""
        try:
            # Extract estimate number from URL
            url_parts = urlparse(url)
            filename = os.path.basename(url_parts.path)
            if filename.endswith('.txt'):
                base_name = filename.replace('.txt', '')
                match = re.search(r'(\d{3})$', base_name)
                if match:
                    estimate_no = match.group(1)
                    self.set_estimate_number(estimate_no)
            
            # Fetch and parse content
            content = self.fetch_from_url(url)
            return self.parse_content(content)
            
        except Exception as e:
            logger.error(f"Error parsing CAS145 from URL {url}: {str(e)}")
            return {}

# Initialize scrapers
pets_scraper = CaltransPETSScraper()
cas145_parser = CAS145Parser()

# API Endpoints
@app.get("/")
async def root():
    """Root endpoint with API information"""
    return {
        "message": "Caltrans Payment Tracking API",
        "version": "1.0.0",
        "endpoints": {
            "get_contract_payments": "/contracts/{contract_number}/payments",
            "get_monthly_payments_with_details": "/contracts/{contract_number}/payments/monthly/{month}",
            "health_check": "/health"
        },
        "workflow": {
            "basic_payments": "Scrapes PETS system for payment history",
            "monthly_details": "Scrapes PETS + follows detail_link to get CAS145 estimate details"
        }
    }

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy", "timestamp": datetime.now().isoformat()}

@app.get("/contracts/{contract_number}/payments", response_model=ContractResponse)
async def get_contract_payments(contract_number: str):
    """
    Retrieve complete payment history for a contract (basic PETS data only)
    
    Args:
        contract_number: The contract number to search for (e.g., '033F0704')
    
    Returns:
        Complete contract information including payment history from PETS system
    """
    try:
        logger.info(f"Fetching payment data for contract: {contract_number}")
        
        contract_data = pets_scraper.scrape_contract(contract_number)
        
        if not contract_data or not contract_data.get('contract_details'):
            raise HTTPException(
                status_code=404, 
                detail=f"Contract {contract_number} not found or no data available"
            )
        
        contract_details = contract_data.get('contract_details', {})
        if not contract_details.get('contract_number'):
            contract_details['contract_number'] = contract_number
        
        payment_history = contract_data.get('payment_history', [])
        contact_info = contract_data.get('contact_info', {})
        summary = contract_data.get('summary', {
            'total_payments': 0,
            'total_disbursed': 0.0,
            'total_held': 0.0,
            'latest_payment_date': 'N/A'
        })
        monthly_breakdown = contract_data.get('monthly_breakdown', {})
        
        return ContractResponse(
            contract_details=ContractDetails(**contract_details),
            payment_history=[PaymentRecord(**payment) for payment in payment_history],
            contact_info=ContactInfo(**contact_info),
            summary=PaymentSummary(**summary),
            monthly_breakdown=monthly_breakdown,
            scraped_at=contract_data.get('scraped_at', datetime.now().isoformat())
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error processing contract {contract_number}: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

@app.get("/contracts/{contract_number}/payments/monthly/{month}", response_model=MonthlyPaymentSummary)
async def get_monthly_payments(contract_number: str, month: str):
    """
    Retrieve detailed payment information for a specific month
    
    This endpoint:
    1. Scrapes PETS system to get payment history
    2. Filters payments for the specified month  
    3. For each payment in that month, follows the detail_link
    4. Parses the detailed CAS145 estimate information using main.py parser
    
    Args:
        contract_number: The contract number to search for
        month: Month in YYYY-MM format (e.g., '2024-12' for December 2024)
    
    Note:
        Handles both 2-digit and 4-digit year formats in payment dates (e.g., "12/06/24" or "12/06/2024")
    
    Returns:
        Monthly payment summary with detailed CAS145 estimate data for each payment
    """
    try:
        # Validate month format
        try:
            datetime.strptime(month, '%Y-%m')
        except ValueError:
            raise HTTPException(
                status_code=400, 
                detail="Month must be in YYYY-MM format (e.g., '2024-12')"
            )
        
        logger.info(f"Fetching detailed monthly payment data for contract: {contract_number}, month: {month}")
        
        contract_data = pets_scraper.scrape_contract(contract_number)
        
        if not contract_data or not contract_data.get('payment_history'):
            raise HTTPException(
                status_code=404, 
                detail=f"Contract {contract_number} not found or no payment history available"
            )
        
        monthly_payments = []
        total_disbursed = 0.0
        total_held = 0.0
        
        for payment in contract_data['payment_history']:
            if payment['release_date'] and payment['release_date'] != 'N/A':
                try:
                    date_obj = pets_scraper.parse_payment_date(payment['release_date'])
                    
                    payment_month = date_obj.strftime('%Y-%m')
                    
                    if payment_month == month:
                        monthly_payments.append(payment)
                        total_disbursed += payment['disbursed_amount']
                        total_held += payment['held_amount']
                except ValueError:
                    continue
        
        if not monthly_payments:
            raise HTTPException(
                status_code=404, 
                detail=f"No payments found for contract {contract_number} in month {month}"
            )
        
        detailed_monthly_payments = []
        
        for payment in monthly_payments:
            detailed_payment = payment.copy()
            
            if payment.get('detail_link'):
                try:
                    logger.info(f"Fetching detailed estimate for payment {payment['estimate_number']} from {payment['detail_link']}")
                    
                    parser = CAS145Parser()
                    
                    detailed_estimate = parser.parse_from_url(payment['detail_link'])
                    
                    if detailed_estimate:
                        detailed_payment['detailed_estimate'] = detailed_estimate
                        logger.info(f"Successfully parsed detailed estimate for payment {payment['estimate_number']}")
                    else:
                        logger.warning(f"No detailed estimate data found for payment {payment['estimate_number']}")
                        detailed_payment['detailed_estimate'] = None
                        
                except Exception as e:
                    logger.error(f"Error fetching detailed estimate for payment {payment['estimate_number']}: {str(e)}")
                    detailed_payment['detailed_estimate'] = None
            else:
                logger.warning(f"No detail_link found for payment {payment['estimate_number']}")
                detailed_payment['detailed_estimate'] = None
            
            detailed_monthly_payments.append(detailed_payment)
        
        return MonthlyPaymentSummary(
            month=month,
            payment_count=len(detailed_monthly_payments),
            total_disbursed=total_disbursed,
            total_held=total_held,
            payments=[DetailedPaymentRecord(**payment) for payment in detailed_monthly_payments]
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error processing monthly data for contract {contract_number}, month {month}: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


if __name__ == "__main__":
    uvicorn.run(
        "main:app", 
        host="0.0.0.0", 
        port=8000, 
        reload=True,
        log_level="info"
    )