-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathincarnation_calculator.fixed.js
More file actions
681 lines (592 loc) · 24.4 KB
/
incarnation_calculator.fixed.js
File metadata and controls
681 lines (592 loc) · 24.4 KB
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
/**
* INCARNATION TIME CALCULATOR & CONSCIOUSNESS FRAMEWORK
*
* This code calculates the temporal dimensions of a human incarnation
* and provides a framework for contemplating consciousness moments.
*
* Template variables:
* - BIRTH_DATE: Format YYYY.MM.DD (e.g., 1971.10.21)
* - CURRENT_DATE: Auto-calculated or specified
*/
const readline = require('readline');
// DEFAULT CONFIGURATION
const DEFAULT_BIRTH_DATE = "1971.10.21";
// Life expectancy data by region (WHO-based actuarial tables)
const LIFE_EXPECTANCY = {
'North America': { male: 76, female: 81, inter: 72 },
'Western Europe': { male: 79, female: 84, inter: 75 },
'Eastern Europe': { male: 71, female: 79, inter: 67 },
'East Asia': { male: 78, female: 84, inter: 74 },
'South Asia': { male: 69, female: 72, inter: 65 },
'Southeast Asia': { male: 71, female: 76, inter: 67 },
'Latin America': { male: 72, female: 78, inter: 68 },
'Middle East': { male: 74, female: 77, inter: 70 },
'Sub-Saharan Africa': { male: 61, female: 65, inter: 57 },
'Oceania': { male: 78, female: 83, inter: 74 },
};
// Power calculation helpers
const sumLinear = (n) => n > 0 ? (n * (n + 1)) / 2 : 0;
const sumSquares = (a, b) => {
if (a > b || b <= 0) return 0;
const f = (n) => (n * (n + 1) * (2 * n + 1)) / 6;
return f(b) - f(Math.max(0, a - 1));
};
const formatNumber = (n) => {
if (n >= 1e12) return (n / 1e12).toFixed(1) + 'T';
if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B';
if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
return n.toLocaleString();
};
// Map country codes to life expectancy regions
const COUNTRY_TO_REGION = {
// North America
US: 'North America', CA: 'North America', MX: 'North America',
// Western Europe
GB: 'Western Europe', FR: 'Western Europe', DE: 'Western Europe',
IT: 'Western Europe', ES: 'Western Europe', NL: 'Western Europe',
BE: 'Western Europe', CH: 'Western Europe', AT: 'Western Europe',
SE: 'Western Europe', NO: 'Western Europe', DK: 'Western Europe',
FI: 'Western Europe', IE: 'Western Europe', PT: 'Western Europe',
LU: 'Western Europe', IS: 'Western Europe',
// Eastern Europe
RU: 'Eastern Europe', PL: 'Eastern Europe', UA: 'Eastern Europe',
CZ: 'Eastern Europe', RO: 'Eastern Europe', HU: 'Eastern Europe',
SK: 'Eastern Europe', BG: 'Eastern Europe', RS: 'Eastern Europe',
HR: 'Eastern Europe', LT: 'Eastern Europe', LV: 'Eastern Europe',
EE: 'Eastern Europe', SI: 'Eastern Europe', BA: 'Eastern Europe',
// East Asia
JP: 'East Asia', CN: 'East Asia', KR: 'East Asia',
TW: 'East Asia', HK: 'East Asia', MN: 'East Asia',
// South Asia
IN: 'South Asia', PK: 'South Asia', BD: 'South Asia',
LK: 'South Asia', NP: 'South Asia',
// Southeast Asia
TH: 'Southeast Asia', VN: 'Southeast Asia', PH: 'Southeast Asia',
ID: 'Southeast Asia', MY: 'Southeast Asia', SG: 'Southeast Asia',
MM: 'Southeast Asia', KH: 'Southeast Asia', LA: 'Southeast Asia',
// Latin America
BR: 'Latin America', AR: 'Latin America', CO: 'Latin America',
CL: 'Latin America', PE: 'Latin America', VE: 'Latin America',
EC: 'Latin America', BO: 'Latin America', PY: 'Latin America',
UY: 'Latin America', CR: 'Latin America', PA: 'Latin America',
CU: 'Latin America', DO: 'Latin America', GT: 'Latin America',
HN: 'Latin America', SV: 'Latin America', NI: 'Latin America',
// Middle East
SA: 'Middle East', AE: 'Middle East', IL: 'Middle East',
TR: 'Middle East', IR: 'Middle East', IQ: 'Middle East',
JO: 'Middle East', LB: 'Middle East', KW: 'Middle East',
QA: 'Middle East', BH: 'Middle East', OM: 'Middle East',
EG: 'Middle East', LY: 'Middle East', TN: 'Middle East',
DZ: 'Middle East', MA: 'Middle East',
// Sub-Saharan Africa
NG: 'Sub-Saharan Africa', ZA: 'Sub-Saharan Africa', KE: 'Sub-Saharan Africa',
ET: 'Sub-Saharan Africa', GH: 'Sub-Saharan Africa', TZ: 'Sub-Saharan Africa',
UG: 'Sub-Saharan Africa', CI: 'Sub-Saharan Africa', CM: 'Sub-Saharan Africa',
SN: 'Sub-Saharan Africa', ZW: 'Sub-Saharan Africa', MZ: 'Sub-Saharan Africa',
AO: 'Sub-Saharan Africa', CD: 'Sub-Saharan Africa', SD: 'Sub-Saharan Africa',
// Oceania
AU: 'Oceania', NZ: 'Oceania', FJ: 'Oceania', PG: 'Oceania',
};
// Look up region from IP geolocation
async function detectRegionFromIP() {
const http = require('http');
return new Promise((resolve, reject) => {
const req = http.get('http://ip-api.com/json/?fields=countryCode,country', (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
try {
const json = JSON.parse(data);
const region = COUNTRY_TO_REGION[json.countryCode];
if (region) {
resolve({ region, country: json.country });
} else {
reject(new Error(`No region mapping for ${json.country} (${json.countryCode})`));
}
} catch (e) {
reject(new Error('Failed to parse geolocation response'));
}
});
});
req.on('error', reject);
req.setTimeout(5000, () => { req.destroy(); reject(new Error('Geolocation request timed out')); });
});
}
// Parse command line arguments
function parseArgs(args) {
const parsed = {};
for (let i = 0; i < args.length; i++) {
if (args[i] === '--birth' && args[i + 1]) {
parsed.birth = args[++i];
} else if (args[i] === '--sex' && args[i + 1]) {
parsed.sex = args[++i].toLowerCase();
} else if (args[i] === '--region' && args[i + 1]) {
parsed.region = args[++i];
} else if (args[i] === '--oura-token' && args[i + 1]) {
parsed.ouraToken = args[++i];
} else if (args[i] === '--live') {
parsed.live = true;
} else if (args[i] === '--auto-region') {
parsed.autoRegion = true;
}
}
return parsed;
}
// Fetch Oura personal info
async function fetchOuraInfo(token) {
const https = require('https');
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.ouraring.com',
path: '/v2/usercollection/personal_info',
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => {
if (res.statusCode === 200) {
try {
resolve(JSON.parse(data));
} catch (e) {
reject(new Error('Failed to parse Oura response'));
}
} else {
reject(new Error(`Oura API error: ${res.statusCode}`));
}
});
});
req.on('error', reject);
req.end();
});
}
// Interactive prompts
async function promptUser(rl, question) {
return new Promise((resolve) => {
rl.question(question, (answer) => {
resolve(answer.trim());
});
});
}
async function getInteractiveInput(existingArgs = {}) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const result = { ...existingArgs };
try {
if (!result.birth) {
result.birth = await promptUser(rl, 'Birth date (YYYY.MM.DD): ');
}
if (!result.sex) {
console.log('\nSex options: male, female, inter');
result.sex = await promptUser(rl, 'Sex: ');
result.sex = result.sex.toLowerCase();
}
if (!result.region) {
const regions = Object.keys(LIFE_EXPECTANCY);
console.log('\nRegions:');
regions.forEach((r, i) => console.log(` ${i + 1}. ${r}`));
const regionChoice = await promptUser(rl, 'Region (number or name): ');
const num = parseInt(regionChoice);
if (num >= 1 && num <= regions.length) {
result.region = regions[num - 1];
} else {
result.region = regions.find(r => r.toLowerCase() === regionChoice.toLowerCase()) || regionChoice;
}
}
} finally {
rl.close();
}
return result;
}
class IncarnationCalculator {
constructor(birthDateString, currentDate = new Date()) {
// Fallback to DEFAULT_BIRTH_DATE inside (avoid subtle default-param issues)
const useBirth = birthDateString || DEFAULT_BIRTH_DATE;
// Parse birth date from format YYYY.MM.DD
const [year, month, day] = useBirth.split('.').map(Number);
this.birthDate = new Date(year, month - 1, day); // month is 0-indexed
this.currentDate = currentDate;
this.timeDifference = this.currentDate.getTime() - this.birthDate.getTime();
// Life expectancy fields (set via setLifeExpectancy)
this.projectedEndDate = null;
this.lifeExpectancyYears = null;
this.sex = null;
this.region = null;
}
setLifeExpectancy(sex, region) {
this.sex = sex;
this.region = region;
if (LIFE_EXPECTANCY[region] && LIFE_EXPECTANCY[region][sex]) {
this.lifeExpectancyYears = LIFE_EXPECTANCY[region][sex];
this.projectedEndDate = new Date(this.birthDate);
this.projectedEndDate.setFullYear(this.birthDate.getFullYear() + this.lifeExpectancyYears);
}
}
getAllTimeUnits() {
const seconds = Math.floor(this.timeDifference / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const weeks = Math.floor(days / 7);
// More precise month/year calculation
let years = this.currentDate.getFullYear() - this.birthDate.getFullYear();
const monthDelta = this.currentDate.getMonth() - this.birthDate.getMonth();
if (monthDelta < 0 || (monthDelta === 0 && this.currentDate.getDate() < this.birthDate.getDate())) {
years--;
}
const monthsDiff = (this.currentDate.getFullYear() - this.birthDate.getFullYear()) * 12 +
(this.currentDate.getMonth() - this.birthDate.getMonth());
let totalMonths = monthsDiff;
if (this.currentDate.getDate() < this.birthDate.getDate()) {
totalMonths -= 1;
}
return {
seconds,
minutes,
hours,
days,
weeks,
months: totalMonths,
years
};
}
getDaysMetrics() {
const times = this.getAllTimeUnits();
const daysLived = times.days;
if (!this.projectedEndDate) {
return {
daysLived,
daysRemaining: null,
totalDays: null,
progress: null
};
}
const msPerDay = 86400000;
const totalDays = Math.floor((this.projectedEndDate.getTime() - this.birthDate.getTime()) / msPerDay);
const daysRemaining = Math.floor((this.projectedEndDate.getTime() - this.currentDate.getTime()) / msPerDay);
const progress = totalDays > 0 ? daysLived / totalDays : 0;
return {
daysLived,
daysRemaining,
totalDays,
progress
};
}
getPowerMetrics() {
const days = this.getDaysMetrics();
if (days.totalDays === null) {
return {
missionCompletion: null,
powerRemaining: null
};
}
// Linear power (mission completion)
const powerGenerated = sumLinear(days.daysLived);
const powerTotal = sumLinear(days.totalDays);
const missionPct = powerTotal > 0 ? (powerGenerated / powerTotal) * 100 : 0;
// Quadratic power (power remaining)
const powerRemainingSq = sumSquares(days.daysLived + 1, days.totalDays);
const powerTotalSq = sumSquares(1, days.totalDays);
const powerRemainingPct = powerTotalSq > 0 ? (powerRemainingSq / powerTotalSq) * 100 : 0;
return {
missionCompletion: {
generated: powerGenerated,
total: powerTotal,
percent: missionPct
},
powerRemaining: {
remaining: powerRemainingSq,
total: powerTotalSq,
percent: powerRemainingPct
}
};
}
getConsciousnessMoments() {
const times = this.getAllTimeUnits();
const days = this.getDaysMetrics();
// Consciousness moment estimates based on research
const momentEstimates = {
// Fast conscious processing (13-300ms average ~150ms)
fastProcessing: Math.floor(times.seconds / 0.15),
// Attention switching/cognitive moments (200-500ms average ~350ms)
cognitiveModerate: Math.floor(times.seconds / 0.35),
// Complete thought cycles (1-3s average ~2s)
thoughtCycles: Math.floor(times.seconds / 2),
// Theta wave consciousness cycles (~125-250ms average ~200ms)
thetaCycles: Math.floor(times.seconds / 0.2)
};
// Use cognitive moderate as our "median moment"
const medianMoments = momentEstimates.cognitiveModerate;
// Calculate projected moments remaining
let projectedMomentsRemaining = null;
if (days.daysRemaining !== null) {
const secondsRemaining = days.daysRemaining * 86400;
projectedMomentsRemaining = Math.floor(secondsRemaining / 0.35);
}
return {
...momentEstimates,
medianMoments,
projectedMomentsRemaining
};
}
generateSummary() {
const times = this.getAllTimeUnits();
const consciousness = this.getConsciousnessMoments();
const days = this.getDaysMetrics();
const power = this.getPowerMetrics();
return {
incarnationStart: this.birthDate.toISOString().split('T')[0],
projectedEnd: this.projectedEndDate ? this.projectedEndDate.toISOString().split('T')[0] : null,
calculationDate: this.currentDate.toISOString().split('T')[0],
timeUnits: times,
daysMetrics: days,
powerMetrics: power,
consciousnessAnalysis: consciousness
};
}
formatOutput() {
const summary = this.generateSummary();
console.log("=".repeat(60));
console.log("INCARNATION TEMPORAL ANALYSIS");
console.log("=".repeat(60));
console.log(`Birth Date: ${summary.incarnationStart}`);
if (summary.projectedEnd) {
console.log(`Projected End: ${summary.projectedEnd}`);
}
console.log(`Analysis Date: ${summary.calculationDate}`);
console.log("");
// Days section
if (summary.daysMetrics.daysRemaining !== null) {
console.log("DAYS:");
console.log(` Days Incarnation: ${summary.daysMetrics.daysLived.toLocaleString()}`);
console.log(` Days Remaining: ${summary.daysMetrics.daysRemaining.toLocaleString()}`);
console.log("");
// Mission completion (linear)
const mc = summary.powerMetrics.missionCompletion;
console.log("MISSION COMPLETION (linear: day d = d):");
console.log(` Σ(1 to ${summary.daysMetrics.daysLived.toLocaleString()}) = ${formatNumber(mc.generated)} / ${formatNumber(mc.total)}`);
console.log(` Progress: ${mc.percent.toFixed(0)}%`);
console.log("");
// Power remaining (quadratic)
const pr = summary.powerMetrics.powerRemaining;
console.log("POWER REMAINING (quadratic: day d = d²):");
console.log(` ${formatNumber(pr.remaining)} / ${formatNumber(pr.total)}`);
console.log(` Remaining: ${pr.percent.toFixed(0)}%`);
console.log("");
}
// Consciousness moments
console.log("CONSCIOUSNESS MOMENTS:");
console.log(` Estimated Moments (lived): ${formatNumber(summary.consciousnessAnalysis.medianMoments)}`);
if (summary.consciousnessAnalysis.projectedMomentsRemaining !== null) {
console.log(` Projected Moments Remaining: ${formatNumber(summary.consciousnessAnalysis.projectedMomentsRemaining)}`);
}
console.log("");
// Time units
console.log("TIME UNITS:");
Object.entries(summary.timeUnits).forEach(([unit, value]) => {
console.log(` ${unit.charAt(0).toUpperCase() + unit.slice(1)}: ${value.toLocaleString()}`);
});
console.log("=".repeat(60));
return summary;
}
}
// SERIALIZABLE ESSENCE FOR LLM CONTEXT
const incarnationEssence = {
concept: "Temporal Analysis of Human Consciousness",
framework: {
timeCalculation: "Convert lifespan to all temporal units (seconds through years)",
consciousnessQuantification: "Estimate discrete moments of awareness (~200-500ms each)",
powerModels: "Linear (mission completion) and quadratic (power remaining) day weighting",
lifeProjection: "WHO-based regional life expectancy tables"
},
researchBasis: {
consciousnessMoments: "100-500ms for cognitive processing cycles",
reactionTimes: "150-300ms for conscious responses",
thoughtTransitions: "1-3 seconds for complete thoughts",
attentionSwitching: "200-500ms between focuses"
},
templateVariables: {
birthDate: "Format YYYY.MM.DD",
sex: "male | female | inter",
region: "Regional life expectancy lookup",
calculationMoment: "Current timestamp or specified date"
},
outputDimensions: [
"seconds", "minutes", "hours", "days", "weeks", "months", "years",
"consciousMoments", "missionCompletion", "powerRemaining"
]
};
// Export for use in other contexts (no side-effects on require/import)
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
IncarnationCalculator,
incarnationEssence,
DEFAULT_BIRTH_DATE,
LIFE_EXPECTANCY,
sumLinear,
sumSquares,
formatNumber
};
}
// Live countdown mode
function runCountdown(calculator) {
const birthYear = calculator.birthDate.getFullYear();
const endYear = calculator.projectedEndDate
? calculator.projectedEndDate.getFullYear()
: '??';
// Hide cursor
process.stdout.write('\x1b[?25l');
const interval = setInterval(() => {
// Update current time and recalculate
calculator.currentDate = new Date();
calculator.timeDifference = calculator.currentDate.getTime() - calculator.birthDate.getTime();
const days = calculator.getDaysMetrics();
const times = calculator.getAllTimeUnits();
const power = calculator.getPowerMetrics();
// Compute live countdown components from remaining time
let remaining = '';
if (days.daysRemaining !== null) {
const totalSec = Math.max(0, Math.floor(
(calculator.projectedEndDate.getTime() - calculator.currentDate.getTime()) / 1000
));
const d = Math.floor(totalSec / 86400);
const h = Math.floor((totalSec % 86400) / 3600);
const m = Math.floor((totalSec % 3600) / 60);
const s = totalSec % 60;
remaining = `${d}d ${String(h).padStart(2, '0')}h ${String(m).padStart(2, '0')}m ${String(s).padStart(2, '0')}s`;
}
// Clear screen and move cursor to top-left
process.stdout.write('\x1b[2J\x1b[H');
const mc = power.missionCompletion;
const pr = power.powerRemaining;
const lines = [
'══════════════════════════════════════════',
' INCARNATION LIVE COUNTDOWN',
'══════════════════════════════════════════',
'',
` ${birthYear} ──────────────────── ${endYear} (${calculator.lifeExpectancyYears || '??'} years)`,
'',
` Years lived: ${times.years}`,
` Days lived: ${days.daysLived.toLocaleString()}`,
` Years remaining: ${calculator.lifeExpectancyYears ? calculator.lifeExpectancyYears - times.years : 'N/A'}`,
` Days remaining: ${days.daysRemaining !== null ? days.daysRemaining.toLocaleString() : 'N/A'}`,
'',
` ⏱ ${remaining}`,
'',
];
if (mc && pr) {
const progressBar = (pct, width = 20) => {
const filled = Math.round((pct / 100) * width);
return '█'.repeat(filled) + '░'.repeat(width - filled);
};
lines.push(
` Mission: ${progressBar(mc.percent)} ${mc.percent.toFixed(1)}%`,
` Power: ${progressBar(pr.percent)} ${pr.percent.toFixed(1)}%`,
);
}
lines.push(
'',
'══════════════════════════════════════════',
' Ctrl+C to exit',
);
console.log(lines.join('\n'));
}, 1000);
// Clean exit on Ctrl+C
process.on('SIGINT', () => {
clearInterval(interval);
// Show cursor
process.stdout.write('\x1b[?25h');
console.log('\n Be well. Use your remaining time wisely.\n');
process.exit(0);
});
}
// Main execution
async function main() {
const args = parseArgs(process.argv.slice(2));
let inputData = { ...args };
console.log("Running Incarnation Calculator...\n");
// If Oura token provided, fetch user info
if (args.ouraToken) {
try {
console.log("Fetching Oura personal info...");
const ouraInfo = await fetchOuraInfo(args.ouraToken);
if (ouraInfo.age) {
const currentYear = new Date().getFullYear();
const birthYear = currentYear - ouraInfo.age;
inputData.birth = `${birthYear}.01.01`; // Approximate to Jan 1
console.log(` Age from Oura: ${ouraInfo.age}`);
}
if (ouraInfo.biological_sex) {
inputData.sex = ouraInfo.biological_sex.toLowerCase();
console.log(` Sex from Oura: ${inputData.sex}`);
}
console.log("");
} catch (error) {
console.log(`Warning: Could not fetch Oura data: ${error.message}`);
console.log("Falling back to manual/interactive input.\n");
}
}
// Auto-detect region from IP if --auto-region or no region provided
if (!inputData.region && (inputData.autoRegion || !inputData.region)) {
try {
console.log("Detecting region from IP address...");
const geo = await detectRegionFromIP();
inputData.region = geo.region;
console.log(` Detected: ${geo.country} → ${geo.region}\n`);
} catch (error) {
console.log(` Could not auto-detect region: ${error.message}`);
console.log(" Falling back to manual selection.\n");
}
}
// If any required fields missing, prompt interactively
if (!inputData.birth || !inputData.sex || !inputData.region) {
inputData = await getInteractiveInput(inputData);
}
// Validate inputs
if (!inputData.birth || !inputData.sex || !inputData.region) {
console.error("Error: Missing required input (birth, sex, or region)");
process.exit(1);
}
// Validate sex
if (!['male', 'female', 'inter'].includes(inputData.sex)) {
console.error("Error: Sex must be male, female, or inter");
process.exit(1);
}
// Validate region
if (!LIFE_EXPECTANCY[inputData.region]) {
console.error(`Error: Unknown region "${inputData.region}"`);
console.error("Valid regions:", Object.keys(LIFE_EXPECTANCY).join(', '));
process.exit(1);
}
console.log("");
// Create calculator and set life expectancy
const calculator = new IncarnationCalculator(inputData.birth);
calculator.setLifeExpectancy(inputData.sex, inputData.region);
calculator.formatOutput();
// Determine if we should enter live countdown mode
let startLive = inputData.live || false;
if (!startLive) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const answer = await promptUser(rl, '\nStart live countdown? (y/n): ');
rl.close();
startLive = answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes';
}
if (startLive) {
runCountdown(calculator);
}
}
// Auto-run only when executed directly (avoid double prints & side effects)
if (typeof require !== 'undefined' && require.main === module) {
main().catch(err => {
console.error("Error:", err.message);
process.exit(1);
});
}