"""Audit raw cancellation fields in a saved CSV, without inferring current validity.""" import argparse,csv,io,json,hashlib from pathlib import Path from collections import Counter def audit(path): data=path.read_bytes();reader=csv.DictReader(io.StringIO(data.decode('utf-8-sig')),strict=True) required={'해제구분','해제일'} if not reader.fieldnames or len(set(reader.fieldnames))!=len(reader.fieldnames) or not required.issubset(reader.fieldnames): raise ValueError('CSV needs unique headers including 해제구분 and 해제일') rows=[];counts=Counter();times=set() for i,row in enumerate(reader,1): if None in row or any(v is None for v in row.values()):raise ValueError('Incomplete or extra CSV fields at data row '+str(i)) marker=row['해제구분'].strip();date=row['해제일'].strip() state='marker_and_date' if marker and date else 'marker_only' if marker else 'date_only' if date else 'both_blank' counts[state]+=1 if row.get('자료저장시각(KST)'):times.add(row['자료저장시각(KST)']) rows.append({'data_row_1based':i,'contract_date':row.get('계약일'),'apartment':row.get('단지명'),'original_marker':row['해제구분'],'original_date':row['해제일'],'field_presence':state}) if not rows:raise ValueError('CSV contains no data rows') return {'kind':'saved CSV raw-field audit, not current contract validity','input_file':path.name,'source_csv_sha256':hashlib.sha256(data).hexdigest(),'snapshot_times_kst':sorted(times),'total_rows':len(rows),'blank_both_fields':counts['both_blank'],'rows_with_any_marker':len(rows)-counts['both_blank'],'marker_and_date':counts['marker_and_date'],'marker_only':counts['marker_only'],'date_only':counts['date_only'],'rows':rows,'limits':'Presence of a saved field only; no current cancellation/validity lookup, no market-price inference.'} if __name__=='__main__': parser=argparse.ArgumentParser();parser.add_argument('--input',required=True,type=Path);parser.add_argument('--output',required=True,type=Path);args=parser.parse_args() if args.input.resolve()==args.output.resolve():raise ValueError('Output must differ from the source CSV') try:result=audit(args.input) except (csv.Error,UnicodeError,ValueError,OSError)as error:parser.exit(2,'Input validation failed: '+str(error)+'\n') with args.output.open('x',encoding='utf-8')as output:json.dump(result,output,ensure_ascii=False,indent=2);output.write('\n')