# Natality Atlas 0.2.0-dev. Source-preserving extraction from annual Stata conversions.
# One output per year; no implicit pooling, clinical recoding, or linkage.
suppressPackageStartupMessages({library(haven);library(jsonlite);library(digest)})
args<-commandArgs(TRUE)
if(length(args)!=3L)stop('Usage: Rscript run_extract.R SPEC.json ANNUAL_STATA_DIR NEW_OUTPUT_DIR')
spec<-fromJSON(args[1],simplifyVector=FALSE)
allowed<-c('version','family','years','variables','population','singletons_only','independent_review','output','dictionary')
if(any(!names(spec)%in%allowed)||spec$version!='0.2.0-dev'||spec$family!='natality')stop('Unsupported specification')
years<-as.integer(unlist(spec$years));variables<-unlist(spec$variables)
if(!length(years)||anyNA(years)||any(!years%in%2014:2024)||anyDuplicated(years))stop('Invalid years')
if(!length(variables)||any(!grepl('^[a-z][a-z0-9_]*$',variables))||anyDuplicated(variables))stop('Invalid variables')
if(!spec$population%in%c('us_residents','all_occurrence')||!is.logical(spec$singletons_only)||length(spec$singletons_only)!=1L)stop('Invalid eligibility criteria')
src<-normalizePath(args[2],mustWork=TRUE)
out<-path.expand(args[3]);if(file.exists(out))stop('Output exists; choose a new directory')
out<-file.path(normalizePath(dirname(out),mustWork=TRUE),basename(out))
if(startsWith(out,paste0(src,'/')))stop('Output must be outside the source directory')
# Preflight every source and field before creating any output.
cols<-unique(c('dob_yy','restatus','dplural',variables))
paths<-file.path(src,paste0('natality',years,'us.dta'))
if(any(!file.exists(paths)))stop('One or more annual sources are absent')
for(i in seq_along(paths)){
 header<-read_dta(paths[i],n_max=0)
 if(any(!cols%in%names(header)))stop(paste('Missing field in',years[i]))
 for(name in variables){
  entries<-Filter(function(v)identical(v$id,name),spec$dictionary)
  if(length(entries)!=1L)stop('Missing variable dictionary entry')
  entry<-Filter(function(v)identical(as.integer(v$year),years[i]),entries[[1]]$years)
  if(length(entry)!=1L||is.null(entry[[1]]$position))stop('Unresolved annual source mapping')
 }
}
dir.create(out,recursive=TRUE);out<-normalizePath(out)
if(startsWith(out,paste0(src,'/')))stop('Output must be outside the source directory')
write_json(spec,file.path(out,'specification.json'),pretty=TRUE,auto_unbox=TRUE,null='null')
receipts<-list()
for(i in seq_along(years)){
 y<-years[i];path<-paths[i];before<-file.info(path)[,c('size','mtime')]
 x<-read_dta(path,col_select=all_of(cols));stopifnot(all(!is.na(x$dob_yy)),all(x$dob_yy==y))
 if(any(!x$restatus%in%1:4))stop('Invalid residence code')
 keep_res<-if(spec$population=='us_residents')x$restatus%in%1:3 else rep(TRUE,nrow(x))
 keep_plur<-if(spec$singletons_only)x$dplural%in%1 else rep(TRUE,nrow(x))
 n<-nrow(x);res_n<-sum(keep_res);x<-x[keep_res&keep_plur,,drop=FALSE]
 frequencies<-lapply(names(x),function(k){t<-table(as.character(x[[k]]),useNA='always');data.frame(code=ifelse(is.na(names(t)),'[STATA_MISSING]',names(t)),count=as.integer(t))});names(frequencies)<-names(x)
 # Haven labels and imported storage types remain attached to columns.
 names(x)<-paste0('source_',names(x))
 receipt<-list(year=y,source_file=basename(path),source_sha256=digest(path,algo='sha256',file=TRUE),source_bytes=unname(before$size),input_rows=n,residence_excluded=n-res_n,plurality_excluded=res_n-nrow(x),output_rows=nrow(x),source_status='Existing Stata conversion; original raw release authentication not established',R=R.version.string,haven=as.character(packageVersion('haven')),runner_sha256=digest(file=sub('^--file=','',commandArgs()[grepl('^--file=',commandArgs())]),algo='sha256'))
 if(!identical(before,file.info(path)[,c('size','mtime')]))stop('Source changed during extraction')
 obj<-list(data=x,dictionary=spec$dictionary,specification=spec,receipt=receipt,source_code_frequencies=frequencies)
 dest<-file.path(out,paste0('natality_',y,'_source_extract.rds'));saveRDS(obj,dest,compress='gzip')
 if(!identical(readRDS(dest),obj))stop('RDS round-trip verification failed')
 receipt$output_sha256<-digest(dest,algo='sha256',file=TRUE)
 write_json(receipt,file.path(out,paste0(y,'_receipt.json')),auto_unbox=TRUE,pretty=TRUE)
 receipts[[length(receipts)+1L]]<-receipt
 cat(y,':',nrow(x),'rows saved and verified\n')
}
write_json(list(status='complete',years=receipts,completed_utc=format(Sys.time(),tz='UTC',usetz=TRUE)),file.path(out,'manifest.json'),auto_unbox=TRUE,pretty=TRUE)
