File size: 40,695 Bytes
d431d95
 
 
 
 
0ec6423
d431d95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59924a2
 
 
 
 
d431d95
 
 
 
 
59924a2
 
 
 
 
 
 
 
 
 
 
d431d95
59924a2
d431d95
59924a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d431d95
 
59924a2
 
 
 
d431d95
59924a2
d431d95
 
 
 
59924a2
d431d95
 
59924a2
d431d95
 
 
 
36a0415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d431d95
759d176
d431d95
759d176
d431d95
59924a2
759d176
59924a2
 
 
 
 
759d176
59924a2
759d176
59924a2
 
759d176
59924a2
 
 
 
 
 
759d176
59924a2
 
 
759d176
59924a2
 
d431d95
759d176
d431d95
 
 
59924a2
 
db3733c
 
59924a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
759d176
59924a2
 
 
 
 
 
 
 
 
 
 
759d176
59924a2
 
 
 
 
 
 
 
 
 
759d176
59924a2
 
 
 
d431d95
 
 
59924a2
 
 
 
 
759d176
59924a2
 
 
 
 
 
 
 
 
 
d431d95
 
759d176
d431d95
 
 
759d176
 
d431d95
 
 
59924a2
 
d431d95
 
59924a2
d431d95
 
59924a2
d431d95
 
759d176
d431d95
 
 
 
759d176
d431d95
 
 
 
 
759d176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d431d95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b50d2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d431d95
 
 
 
 
5897d8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fd03ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5897d8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d431d95
 
 
 
 
 
 
 
 
 
 
 
0ec6423
d431d95
 
 
0ec6423
d431d95
 
0ec6423
d431d95
 
 
0ec6423
 
 
 
 
 
 
 
 
 
 
 
 
 
d431d95
0ec6423
 
d431d95
 
 
0ec6423
 
 
d431d95
 
 
 
 
 
8fd03ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52bc805
0ec6423
52bc805
 
 
 
0ec6423
52bc805
 
 
0ec6423
 
 
 
 
52bc805
 
0ec6423
52bc805
0ec6423
 
52bc805
 
 
 
 
0ec6423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52bc805
 
 
0ec6423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52bc805
 
 
 
 
d431d95
 
 
 
 
 
 
 
 
8fd03ae
d431d95
 
8fd03ae
 
d431d95
 
 
 
 
 
 
0ec6423
d431d95
 
0ec6423
d431d95
 
59924a2
d431d95
59924a2
d431d95
 
 
 
0ec6423
8fd03ae
 
 
 
 
 
 
52bc805
0ec6423
 
d431d95
36a0415
d431d95
759d176
d431d95
2b50d2d
 
 
d431d95
5897d8c
 
0ec6423
d431d95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ec6423
 
 
 
 
 
 
 
 
 
 
 
d431d95
0ec6423
d431d95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env node

import { readFileSync, writeFileSync, existsSync } from 'fs';
import { join, dirname, basename, extname } from 'path';
import { fileURLToPath } from 'url';
import { extractAndGenerateFrontmatter } from './metadata-extractor.mjs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Configuration
const DEFAULT_INPUT = join(__dirname, 'output', 'main.md');
const DEFAULT_OUTPUT = join(__dirname, 'output', 'main.mdx');

function parseArgs() {
    const args = process.argv.slice(2);
    const config = {
        input: DEFAULT_INPUT,
        output: DEFAULT_OUTPUT,
    };

    for (const arg of args) {
        if (arg.startsWith('--input=')) {
            config.input = arg.substring('--input='.length);
        } else if (arg.startsWith('--output=')) {
            config.output = arg.substring('--output='.length);
        } else if (arg === '--help' || arg === '-h') {
            console.log(`
πŸ“ Markdown to MDX Converter

Usage:
  node mdx-converter.mjs [options]

Options:
  --input=PATH     Input Markdown file (default: ${DEFAULT_INPUT})
  --output=PATH    Output MDX file (default: ${DEFAULT_OUTPUT})
  --help, -h       Show this help

Examples:
  # Basic conversion
  node mdx-converter.mjs

  # Custom paths
  node mdx-converter.mjs --input=article.md --output=article.mdx
            `);
            process.exit(0);
        } else if (!config.input) {
            config.input = arg;
        } else if (!config.output) {
            config.output = arg;
        }
    }
    return config;
}

/**
 * Modular MDX post-processing functions for Astro compatibility
 * Each function handles a specific type of transformation
 */

/**
 * Track which Astro components are used during transformations
 */
const usedComponents = new Set();

/**
 * Track individual image imports needed
 */
const imageImports = new Map(); // src -> varName

/**
 * Add required component imports to the frontmatter
 * @param {string} content - MDX content
 * @returns {string} - Content with component imports
 */
/**
 * Generate a variable name from image path
 * @param {string} src - Image source path
 * @returns {string} - Valid variable name
 */
function generateImageVarName(src) {
    // Extract filename without extension and make it a valid JS variable
    const filename = src.split('/').pop().replace(/\.[^.]+$/, '');
    return filename.replace(/[^a-zA-Z0-9]/g, '_').replace(/^[0-9]/, 'img_$&');
}

function addComponentImports(content) {
    console.log('  πŸ“¦ Adding component and image imports...');

    let imports = [];

    // Add component imports
    if (usedComponents.size > 0) {
        const componentImports = Array.from(usedComponents)
            .map(component => `import ${component} from '../components/${component}.astro';`);
        imports.push(...componentImports);
        console.log(`    βœ… Importing components: ${Array.from(usedComponents).join(', ')}`);
    }

    // Add image imports
    if (imageImports.size > 0) {
        const imageImportStatements = Array.from(imageImports.entries())
            .map(([src, varName]) => `import ${varName} from '${src}';`);
        imports.push(...imageImportStatements);
        console.log(`    βœ… Importing ${imageImports.size} image(s)`);
    }

    if (imports.length === 0) {
        console.log('    ℹ️  No imports needed');
        return content;
    }

    const importBlock = imports.join('\n');

    // Insert imports after frontmatter
    const frontmatterEnd = content.indexOf('---', 3) + 3;
    if (frontmatterEnd > 2) {
        return content.slice(0, frontmatterEnd) + '\n\n' + importBlock + '\n' + content.slice(frontmatterEnd);
    } else {
        // No frontmatter, add at beginning
        return importBlock + '\n\n' + content;
    }
}


/**
 * Convert grouped figures (subfigures) to MultiImage components
 * @param {string} content - MDX content
 * @returns {string} - Content with MultiImage components for grouped figures
 */
function convertSubfiguresToMultiImage(content) {
    console.log('  πŸ–ΌοΈβœ¨ Converting subfigures to MultiImage components...');

    let convertedCount = 0;

    // Pattern to match: <figure> containing multiple <figure> elements with a global caption
    // This matches the LaTeX subfigure pattern that gets converted by Pandoc
    const subfigureGroupPattern = /<figure>\s*((?:<figure>[\s\S]*?<\/figure>\s*){2,})<figcaption>([\s\S]*?)<\/figcaption>\s*<\/figure>/g;

    const convertedContent = content.replace(subfigureGroupPattern, (match, figuresMatch, globalCaption) => {
        convertedCount++;

        // Extract individual figures within the group
        // This pattern is more flexible to handle variations in HTML structure
        const individualFigurePattern = /<figure>\s*<img src="([^"]*)"[^>]*\/>\s*<p>&lt;span id="([^"]*)"[^&]*&gt;&lt;\/span&gt;<\/p>\s*<figcaption>([\s\S]*?)<\/figcaption>\s*<\/figure>/g;

        const images = [];
        let figureMatch;

        while ((figureMatch = individualFigurePattern.exec(figuresMatch)) !== null) {
            const [, src, id, caption] = figureMatch;

            // Clean the source path (similar to existing transformImages function)
            const cleanSrc = src.replace(/.*\/output\/assets\//, './assets/')
                .replace(/\/Users\/[^\/]+\/[^\/]+\/[^\/]+\/[^\/]+\/[^\/]+\/app\/scripts\/latex-to-markdown\/output\/assets\//, './assets/');

            // Clean caption text (remove HTML, normalize whitespace)
            const cleanCaption = caption
                .replace(/<[^>]*>/g, '')
                .replace(/\n/g, ' ')
                .replace(/\s+/g, ' ')
                .replace(/'/g, "\\'")
                .trim();

            // Generate alt text from caption
            const altText = cleanCaption.length > 100
                ? cleanCaption.substring(0, 100) + '...'
                : cleanCaption;

            // Generate variable name for import
            const varName = generateImageVarName(cleanSrc);
            imageImports.set(cleanSrc, varName);

            images.push({
                src: varName,
                alt: altText,
                caption: cleanCaption,
                id: id
            });
        }

        // Clean global caption
        const cleanGlobalCaption = globalCaption
            .replace(/<[^>]*>/g, '')
            .replace(/\n/g, ' ')
            .replace(/\s+/g, ' ')
            .replace(/'/g, "\\'")
            .trim();

        // Mark MultiImage component as used
        usedComponents.add('MultiImage');

        // Determine layout based on number of images
        let layout = 'auto';
        if (images.length === 2) layout = '2-column';
        else if (images.length === 3) layout = '3-column';
        else if (images.length === 4) layout = '4-column';

        // Generate MultiImage component
        const imagesJson = images.map(img =>
            `    {\n      src: ${img.src},\n      alt: "${img.alt}",\n      caption: "${img.caption}",\n      id: "${img.id}"\n    }`
        ).join(',\n');

        return `<MultiImage
  images={[
${imagesJson}
  ]}
  layout="${layout}"
  zoomable
  downloadable
  caption="${cleanGlobalCaption}"
/>`;
    });

    if (convertedCount > 0) {
        console.log(`    βœ… Converted ${convertedCount} subfigure group(s) to MultiImage component(s)`);
    } else {
        console.log('    ℹ️  No subfigure groups found');
    }

    return convertedContent;
}

/**
 * Transform images to Image components
 * @param {string} content - MDX content
 * @returns {string} - Content with Image components
 */
/**
 * Create Image component with import
 * @param {string} src - Clean image source
 * @param {string} alt - Alt text  
 * @param {string} id - Element ID
 * @param {string} caption - Figure caption
 * @param {string} width - Optional width
 * @returns {string} - Image component markup
 */
function createImageComponent(src, alt = '', id = '', caption = '', width = '') {
    const varName = generateImageVarName(src);
    imageImports.set(src, varName);
    usedComponents.add('Image');

    const props = [];
    props.push(`src={${varName}}`);
    props.push('zoomable');
    props.push('downloadable');
    if (id) props.push(`id="${id}"`);
    if (width) props.push(`width={${width}}`);
    if (alt) props.push(`alt="${alt}"`);
    if (caption) props.push(`caption={'${caption}'}`);

    return `<Image\n  ${props.join('\n  ')}\n/>`;
}

function transformImages(content) {
    console.log('  πŸ–ΌοΈ  Transforming images to Image components with imports...');

    let hasImages = false;

    // Helper function to clean source paths
    const cleanSrcPath = (src) => {
        return src.replace(/.*\/output\/assets\//, './assets/')
            .replace(/\/Users\/[^\/]+\/[^\/]+\/[^\/]+\/[^\/]+\/[^\/]+\/app\/scripts\/latex-to-markdown\/output\/assets\//, './assets/');
    };

    // Helper to clean caption text
    const cleanCaption = (caption) => {
        return caption
            .replace(/<[^>]*>/g, '')          // Remove HTML tags
            .replace(/\n/g, ' ')              // Replace newlines with spaces
            .replace(/\r/g, ' ')              // Replace carriage returns with spaces
            .replace(/\s+/g, ' ')             // Replace multiple spaces with single space
            .replace(/'/g, "\\'")             // Escape quotes
            .trim();                          // Trim whitespace
    };

    // Helper to clean alt text
    const cleanAltText = (alt, maxLength = 100) => {
        const cleaned = alt
            .replace(/<[^>]*>/g, '')          // Remove HTML tags
            .replace(/\n/g, ' ')              // Replace newlines with spaces
            .replace(/\r/g, ' ')              // Replace carriage returns with spaces
            .replace(/\s+/g, ' ')             // Replace multiple spaces with single space
            .trim();                          // Trim whitespace

        return cleaned.length > maxLength
            ? cleaned.substring(0, maxLength) + '...'
            : cleaned;
    };

    // 1. Transform complex HTML figures with style attributes
    content = content.replace(
        /<figure id="([^"]*)">\s*<img src="([^"]*)"(?:\s+style="([^"]*)")?\s*\/>\s*<figcaption>\s*(.*?)\s*<\/figcaption>\s*<\/figure>/gs,
        (match, id, src, style, caption) => {
            const cleanSrc = cleanSrcPath(src);
            const cleanCap = cleanCaption(caption);
            const altText = cleanAltText(cleanCap);
            hasImages = true;

            return createImageComponent(cleanSrc, altText, id, cleanCap);
        }
    );

    // 2. Transform standalone img tags with style
    content = content.replace(
        /<img src="([^"]*)"(?:\s+style="([^"]*)")?\s*(?:alt="([^"]*)")?\s*\/>/g,
        (match, src, style, alt) => {
            const cleanSrc = cleanSrcPath(src);
            const cleanAlt = cleanAltText(alt || 'Figure');
            hasImages = true;

            return createImageComponent(cleanSrc, cleanAlt);
        }
    );

    // 3. Transform images within wrapfigure divs
    content = content.replace(
        /<div class="wrapfigure">\s*r[\d.]+\s*<img src="([^"]*)"[^>]*\/>\s*<\/div>/gs,
        (match, src) => {
            const cleanSrc = cleanSrcPath(src);
            hasImages = true;

            return createImageComponent(cleanSrc, 'Figure');
        }
    );

    // 4. Transform simple HTML figure/img without style
    content = content.replace(
        /<figure id="([^"]*)">\s*<img src="([^"]*)" \/>\s*<figcaption>\s*(.*?)\s*<\/figcaption>\s*<\/figure>/gs,
        (match, id, src, caption) => {
            const cleanSrc = cleanSrcPath(src);
            const cleanCap = cleanCaption(caption);
            const altText = cleanAltText(cleanCap);
            hasImages = true;

            return createImageComponent(cleanSrc, altText, id, cleanCap);
        }
    );

    // 5. Clean up figures with minipage divs
    content = content.replace(
        /<figure id="([^"]*)">\s*<div class="minipage">\s*<img src="([^"]*)"[^>]*\/>\s*<\/div>\s*<figcaption[^>]*>(.*?)<\/figcaption>\s*<\/figure>/gs,
        (match, id, src, caption) => {
            const cleanSrc = cleanSrcPath(src);
            const cleanCap = cleanCaption(caption);
            const altText = cleanAltText(cleanCap);
            hasImages = true;

            return createImageComponent(cleanSrc, altText, id, cleanCap);
        }
    );


    // 7. Transform Pandoc-style images: ![alt](src){#id attr="value"}
    content = content.replace(
        /!\[([^\]]*)\]\(([^)]+)\)(?:\{([^}]+)\})?/g,
        (match, alt, src, attributes) => {
            const cleanSrc = cleanSrcPath(src);
            const cleanAlt = cleanAltText(alt || 'Figure');
            hasImages = true;

            let id = '';
            if (attributes) {
                const idMatch = attributes.match(/#([\w-]+)/);
                if (idMatch) id = idMatch[1];
            }

            return createImageComponent(cleanSrc, cleanAlt, id);
        }
    );

    if (hasImages) {
        console.log('    βœ… Image components with imports will be created');
    }

    return content;
}

/**
 * Transform figures with Image components that still have separate figcaptions
 * @param {string} content - MDX content
 * @returns {string} - Content with Image components using caption props
 */
function transformImageFigures(content) {
    console.log('  πŸ”§ Transforming figures with Image components and separate figcaptions...');
    
    let hasTransformed = false;
    
    
    // Transform figures with Image components that still have separate figcaptions
    content = content.replace(
        /<figure>\s*<Image([\s\S]*?)\/>\s*<span[^>]*><\/span>\s*<figcaption>([\s\S]*?)<\/figcaption>\s*<\/figure>/gs,
        (match, imageProps, caption) => {
            hasTransformed = true;
            
            // Clean caption text
            const cleanCap = caption
                .replace(/<[^>]*>/g, '')          // Remove HTML tags
                .replace(/\n/g, ' ')              // Replace newlines with spaces
                .replace(/\r/g, ' ')              // Replace carriage returns with spaces
                .replace(/\s+/g, ' ')             // Replace multiple spaces with single space
                .replace(/'/g, "\\'")             // Escape quotes
                .trim();                          // Trim whitespace

            // Extract the Image component and add the caption prop
            const imageComponent = `<Image${imageProps} caption={'${cleanCap}'}/>`;
            return imageComponent;
        }
    );
    
    // Also try a more flexible pattern that handles escaped HTML
    content = content.replace(
        /<figure>\s*<Image([\s\S]*?)\/>\s*<p>&lt;span[^&]*&gt;&lt;\/span&gt;<\/p>\s*<figcaption>([\s\S]*?)<\/figcaption>\s*<\/figure>/gs,
        (match, imageProps, caption) => {
            hasTransformed = true;
            
            // Clean caption text
            const cleanCap = caption
                .replace(/<[^>]*>/g, '')          // Remove HTML tags
                .replace(/\n/g, ' ')              // Replace newlines with spaces
                .replace(/\r/g, ' ')              // Replace carriage returns with spaces
                .replace(/\s+/g, ' ')             // Replace multiple spaces with single space
                .replace(/'/g, "\\'")             // Escape quotes
                .trim();                          // Trim whitespace

            // Extract the Image component and add the caption prop
            const imageComponent = `<Image${imageProps} caption={'${cleanCap}'}/>`;
            return imageComponent;
        }
    );
    
    // Handle figures with minipage divs
    content = content.replace(
        /<figure>\s*<div class="minipage">\s*<Image([\s\S]*?)\/>\s*<span[^>]*><\/span>\s*<\/div>\s*<figcaption>([\s\S]*?)<\/figcaption>\s*<\/figure>/gs,
        (match, imageProps, caption) => {
            hasTransformed = true;
            
            // Clean caption text
            const cleanCap = caption
                .replace(/<[^>]*>/g, '')          // Remove HTML tags
                .replace(/\n/g, ' ')              // Replace newlines with spaces
                .replace(/\r/g, ' ')              // Replace carriage returns with spaces
                .replace(/\s+/g, ' ')             // Replace multiple spaces with single space
                .replace(/'/g, "\\'")             // Escape quotes
                .trim();                          // Trim whitespace

            // Extract the Image component and add the caption prop
            const imageComponent = `<Image${imageProps} caption={'${cleanCap}'}/>`;
            return imageComponent;
        }
    );
    
    // Handle figures with minipage divs (escaped HTML version)
    content = content.replace(
        /<figure>\s*<div class="minipage">\s*<Image([\s\S]*?)\/>\s*<p>&lt;span[^&]*&gt;&lt;\/span&gt;<\/p>\s*<\/div>\s*<figcaption>([\s\S]*?)<\/figcaption>\s*<\/figure>/gs,
        (match, imageProps, caption) => {
            hasTransformed = true;
            
            // Clean caption text
            const cleanCap = caption
                .replace(/<[^>]*>/g, '')          // Remove HTML tags
                .replace(/\n/g, ' ')              // Replace newlines with spaces
                .replace(/\r/g, ' ')              // Replace carriage returns with spaces
                .replace(/\s+/g, ' ')             // Replace multiple spaces with single space
                .replace(/'/g, "\\'")             // Escape quotes
                .trim();                          // Trim whitespace

            // Extract the Image component and add the caption prop
            const imageComponent = `<Image${imageProps} caption={'${cleanCap}'}/>`;
            return imageComponent;
        }
    );
    
    if (hasTransformed) {
        console.log('    βœ… Transformed figures with Image components to use caption props');
    } else {
        console.log('    ℹ️  No figures with Image components and separate figcaptions found');
    }
    
    return content;
}

/**
 * Transform HTML spans with style attributes to appropriate components
 * @param {string} content - MDX content  
 * @returns {string} - Content with transformed spans
 */
function transformStyledSpans(content) {
    console.log('  🎨 Transforming styled spans...');

    // Transform HTML spans with style attributes
    content = content.replace(
        /<span style="color: ([^"]+)">(.*?)<\/span>/g,
        (match, color, text) => {
            // Map colors to semantic classes or components
            const colorMap = {
                'hf2': 'text-hf-secondary',
                'hf1': 'text-hf-primary'
            };

            const className = colorMap[color] || `text-${color}`;
            return `<span class="${className}">${text}</span>`;
        }
    );

    // Transform markdown spans with style attributes: [text]{style="color: color"}
    content = content.replace(
        /\[([^\]]+)\]\{style="color: ([^"]+)"\}/g,
        (match, text, color) => {
            // Map colors to semantic classes or components
            const colorMap = {
                'hf2': 'text-hf-secondary',
                'hf1': 'text-hf-primary'
            };

            const className = colorMap[color] || `text-${color}`;
            return `<span class="${className}">${text}</span>`;
        }
    );

    return content;
}

/**
 * Transform epigraph divs to Quote components
 * @param {string} content - MDX content
 * @returns {string} - Content with Quote components
 */
function transformEpigraphs(content) {
    console.log('  πŸ’¬ Transforming epigraphs to Quote components...');

    let epigraphsConverted = 0;

    // Pattern to match epigraph divs: <div class="epigraph">...</div>
    // More flexible pattern that handles various formats
    content = content.replace(
        /<div class="epigraph">([\s\S]*?)<\/div>/g,
        (match, content) => {
            // Extract quote text (between asterisks) and author (last non-empty line)
            const lines = content.trim().split('\n').map(line => line.trim()).filter(line => line);
            
            let quoteText = '';
            let author = '';
            
            // Find quote text (between asterisks)
            const quoteMatch = content.match(/\*([^*]+)\*/);
            if (quoteMatch) {
                quoteText = quoteMatch[1].trim();
            }
            
            // Find author (usually the last non-empty line that's not the quote)
            const lastLine = lines[lines.length - 1];
            if (lastLine && !lastLine.includes('*') && !lastLine.includes('[')) {
                author = lastLine;
            }
            
            if (quoteText && author) {
                epigraphsConverted++;
                
                // Clean the quote text
                const cleanQuoteText = quoteText
                    .replace(/<[^>]*>/g, '')
                    .replace(/\s+/g, ' ')
                    .replace(/"/g, '\\"')
                    .trim();

                // Clean the author text
                const cleanAuthor = author
                    .replace(/<[^>]*>/g, '')
                    .replace(/\s+/g, ' ')
                    .replace(/"/g, '\\"')
                    .trim();

                // Mark Quote component as used
                usedComponents.add('Quote');

                return `<Quote source="${cleanAuthor}">
  ${cleanQuoteText}
</Quote>`;
            }
            
            return match; // Return original if we can't parse it
        }
    );

    if (epigraphsConverted > 0) {
        console.log(`    βœ… Converted ${epigraphsConverted} epigraph(s) to Quote component(s)`);
    } else {
        console.log('    ℹ️  No epigraphs found');
    }

    return content;
}

/**
 * Transform highlight spans to mark tags
 * @param {string} content - MDX content
 * @returns {string} - Content with mark tags instead of highlight spans
 */
function transformHighlightSpans(content) {
    console.log('  🎯 Transforming highlight spans to mark tags...');

    let highlightsConverted = 0;

    // Transform <span class="highlight">...</span> to <mark>...</mark>
    content = content.replace(
        /<span class="highlight">(.*?)<\/span>/g,
        (match, text) => {
            highlightsConverted++;
            return `<mark>${text}</mark>`;
        }
    );

    if (highlightsConverted > 0) {
        console.log(`    βœ… Converted ${highlightsConverted} highlight span(s) to mark tag(s)`);
    } else {
        console.log('    ℹ️  No highlight spans found');
    }

    return content;
}

/**
 * Fix escaped mark tags
 * @param {string} content - MDX content
 * @returns {string} - Content with unescaped mark tags
 */
function fixEscapedMarkTags(content) {
    console.log('  🎯 Fixing escaped mark tags...');

    let fixedCount = 0;

    // Fix escaped mark tags: \<mark\>...\</mark\> -> <mark>...</mark>
    content = content.replace(
        /\\<mark\\>(.*?)\\<\/mark\\>/g,
        (match, text) => {
            fixedCount++;
            return `<mark>${text}</mark>`;
        }
    );

    if (fixedCount > 0) {
        console.log(`    βœ… Fixed ${fixedCount} escaped mark tag(s)`);
    } else {
        console.log('    ℹ️  No escaped mark tags found');
    }

    return content;
}

/**
 * Transform reference links to proper Astro internal links
 * @param {string} content - MDX content
 * @returns {string} - Content with transformed links
 */
function fixHtmlEscaping(content) {
    console.log('  πŸ”§ Fixing HTML escaping in spans...');

    let fixedCount = 0;

    // Pattern 1: \<span id="..." style="..."\>\</span\>
    content = content.replace(/\\<span id="([^"]*)" style="([^"]*)"\\>\\<\/span\\>/g, (match, id, style) => {
        fixedCount++;
        // Fix common style issues like "position- absolute;" -> "position: absolute;"
        const cleanStyle = style.replace('position- absolute;', 'position: absolute;');
        return `<span id="${id}" style="${cleanStyle}"></span>`;
    });

    // Pattern 2: \<span class="..."\>...\</span\>
    content = content.replace(/\\<span class="([^"]*)"\\>([^\\]+)\\<\/span\\>/g, (match, className, text) => {
        fixedCount++;
        // Remove numbering like (1), (2), (3) from highlight spans
        let cleanText = text;
        if (className === 'highlight') {
            cleanText = text.replace(/^\(\d+\)\s*/, '');
        }
        return `<span class="${className}">${cleanText}</span>`;
    });

    // Pattern 3: HTML-encoded spans in paragraph tags
    // <p>&lt;span id="..." style="..."&gt;&lt;/span&gt;</p>
    content = content.replace(/<p>&lt;span id="([^"]*)" style="([^"]*)"&gt;&lt;\/span&gt;<\/p>/g, (match, id, style) => {
        fixedCount++;
        // Fix common style issues like "position- absolute;" -> "position: absolute;"
        const cleanStyle = style.replace('position- absolute;', 'position: absolute;');
        return `<span id="${id}" style="${cleanStyle}"></span>`;
    });

    // Pattern 4: HTML-encoded spans with class in paragraph tags
    // <p>&lt;span class="..."&gt;...&lt;/span&gt;</p>
    content = content.replace(/<p>&lt;span class="([^"]*)"&gt;([^&]*)&lt;\/span&gt;<\/p>/g, (match, className, text) => {
        fixedCount++;
        // Remove numbering like (1), (2), (3) from highlight spans
        let cleanText = text;
        if (className === 'highlight') {
            cleanText = text.replace(/^\(\d+\)\s*/, '');
        }
        return `<span class="${className}">${cleanText}</span>`;
    });

    if (fixedCount > 0) {
        console.log(`    βœ… Fixed ${fixedCount} escaped span(s)`);
    }

    return content;
}

function cleanHighlightNumbering(content) {
    console.log('  πŸ”’ Removing numbering from highlight spans...');

    let cleanedCount = 0;
    // Clean numbering from non-escaped highlight spans too
    content = content.replace(/<span class="highlight">(\(\d+\)\s*)([^<]+)<\/span>/g, (match, numbering, text) => {
        cleanedCount++;
        return `<span class="highlight">${text}</span>`;
    });

    if (cleanedCount > 0) {
        console.log(`    βœ… Removed numbering from ${cleanedCount} highlight span(s)`);
    }

    return content;
}

function transformReferenceLinks(content) {
    console.log('  πŸ”— Transforming reference links...');

    // Transform Pandoc reference links: [text](#ref){reference-type="ref" reference="ref"}
    return content.replace(
        /\[([^\]]+)\]\((#[^)]+)\)\{[^}]*reference[^}]*\}/g,
        (match, text, href) => {
            return `[${text}](${href})`;
        }
    );
}


/**
 * Fix frontmatter and ensure proper MDX format
 * @param {string} content - MDX content
 * @param {string} latexContent - Original LaTeX content for metadata extraction
 * @returns {string} - Content with proper frontmatter
 */
function ensureFrontmatter(content, latexContent = '') {
    console.log('  πŸ“„ Ensuring proper frontmatter...');

    if (!content.startsWith('---')) {
        let frontmatter;

        if (latexContent) {
            // Extract metadata from LaTeX using dedicated module
            frontmatter = extractAndGenerateFrontmatter(latexContent);
            console.log('    βœ… Generated frontmatter from LaTeX metadata');
        } else {
            // Fallback frontmatter
            const currentDate = new Date().toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'short',
                day: '2-digit'
            });
            frontmatter = `---
title: "Research Article"
published: "${currentDate}"
tableOfContentsAutoCollapse: true
---

`;
            console.log('    βœ… Generated basic frontmatter');
        }

        return frontmatter + content;
    }

    return content;
}

/**
 * Fix mixed math delimiters like $`...`$ or `...`$
 * @param {string} content - MDX content
 * @returns {string} - Content with fixed math delimiters
 */
function fixMixedMathDelimiters(content) {
    console.log('  πŸ”§ Fixing mixed math delimiters...');

    let fixedCount = 0;

    // Fix patterns like $`...`$ (mixed delimiters)
    content = content.replace(/\$`([^`]*)`\$/g, (match, mathContent) => {
        fixedCount++;
        return `$${mathContent}$`;
    });

    // Fix patterns like `...`$ (backtick start, dollar end)
    content = content.replace(/`([^`]*)`\$/g, (match, mathContent) => {
        fixedCount++;
        return `$${mathContent}$`;
    });

    // Fix patterns like $`...` (dollar start, backtick end - less common)
    content = content.replace(/\$`([^`]*)`(?!\$)/g, (match, mathContent) => {
        fixedCount++;
        return `$${mathContent}$`;
    });

    if (fixedCount > 0) {
        console.log(`    βœ… Fixed ${fixedCount} mixed math delimiter(s)`);
    }

    return content;
}

/**
 * Clean up orphaned math delimiters and fix mixed content
 * @param {string} content - MDX content
 * @returns {string} - Content with cleaned math blocks
 */
function cleanOrphanedMathDelimiters(content) {
    console.log('  🧹 Cleaning orphaned math delimiters...');
    console.log('    πŸ” Content length:', content.length, 'chars');

    let fixedCount = 0;

    // Fix orphaned $$ that are alone on lines (but not part of display math blocks)
    // Only remove $$ that appear alone without corresponding closing $$
    content = content.replace(/^\$\$\s*$(?!\s*[\s\S]*?\$\$)/gm, () => {
        fixedCount++;
        return '';
    });

    // Fix backticks inside $$....$$ blocks (Pandoc artifact)
    const mathMatches = content.match(/\$\$([\s\S]*?)\$\$/g);
    console.log(`    πŸ” Found ${mathMatches ? mathMatches.length : 0} math blocks`);

    content = content.replace(/\$\$([\s\S]*?)\$\$/g, (match, mathContent) => {
        // More aggressive: remove ALL single backticks in math blocks (they shouldn't be there)
        let cleanedMath = mathContent;

        // Count backticks before
        const backticksBefore = (mathContent.match(/`/g) || []).length;

        if (backticksBefore > 0) {
            console.log(`    πŸ”§ Found math block with ${backticksBefore} backtick(s)`);
        }

        // Remove all isolated backticks (not in pairs)
        cleanedMath = cleanedMath.replace(/`/g, '');

        const backticksAfter = (cleanedMath.match(/`/g) || []).length;

        if (backticksBefore > 0) {
            fixedCount++;
            console.log(`    πŸ”§ Removed ${backticksBefore} backtick(s) from math block`);
            return `$$${cleanedMath}$$`;
        }
        return match;
    });

    // Fix escaped align in math blocks: \begin{align} -> \begin{align}
    content = content.replace(/\\begin\{align\}/g, (match) => {
        fixedCount++;
        return '\\begin{align}';
    });

    content = content.replace(/\\end\{align\}/g, (match) => {
        fixedCount++;
        return '\\end{align}';
    });

    // Fix cases where text gets mixed with math blocks
    // Pattern: ``` math ... ``` text ``` math 
    content = content.replace(/``` math\s*\n([\s\S]*?)\n```\s*([^`\n]*?)\s*``` math/g, (match, math1, text, math2) => {
        if (text.trim().length > 0 && !text.includes('```')) {
            fixedCount++;
            return '```' + ' math\n' + math1 + '\n```\n\n' + text.trim() + '\n\n```' + ' math';
        }
        return match;
    });

    if (fixedCount > 0) {
        console.log(`    βœ… Fixed ${fixedCount} orphaned math delimiter(s)`);
    }

    return content;
}

/**
 * Clean newlines from single-dollar math blocks ($...$) ONLY
 * @param {string} content - MDX content
 * @returns {string} - Content with cleaned math blocks
 */
function cleanSingleLineMathNewlines(content) {
    console.log('  πŸ”’ Cleaning newlines in single-dollar math blocks ($...$)...');

    let cleanedCount = 0;

    // ULTRA STRICT: Only target single dollar blocks ($...$) that contain newlines
    // Use dotall flag (s) to match newlines with .*, and ensure we don't match $$
    const cleanedContent = content.replace(/\$(?!\$)([\s\S]*?)\$(?!\$)/g, (match, mathContent) => {
        // Only process if the content contains newlines
        if (mathContent.includes('\n')) {
            cleanedCount++;

            // Remove ALL newlines and carriage returns, normalize whitespace
            const cleanedMath = mathContent
                .replace(/\n+/g, ' ')           // Replace all newlines with spaces
                .replace(/\r+/g, ' ')           // Replace carriage returns with spaces  
                .replace(/\s+/g, ' ')           // Normalize multiple spaces to single
                .trim();                        // Remove leading/trailing spaces

            return `$${cleanedMath}$`;
        }
        return match; // Keep original if no newlines
    });

    if (cleanedCount > 0) {
        console.log(`    βœ… Cleaned ${cleanedCount} single-dollar math block(s) with newlines`);
    }

    return cleanedContent;
}

/**
 * Add proper line breaks around display math blocks ($$...$$)
 * @param {string} content - MDX content
 * @returns {string} - Content with properly spaced display math
 */
function formatDisplayMathBlocks(content) {
    console.log('  πŸ“ Formatting display math blocks with proper spacing...');

    let formattedCount = 0;

    // Find all $$...$$$ blocks (display math) and ensure proper line breaks
    // Very strict: only matches exactly $$ followed by content followed by $$
    const formattedContent = content.replace(/\$\$([\s\S]*?)\$\$/g, (match, mathContent) => {
        formattedCount++;

        // Clean up the math content - trim whitespace but preserve structure
        const cleanedMath = mathContent.trim();

        // Return with proper line breaks before and after
        return `\n$$\n${cleanedMath}\n$$\n`;
    });

    if (formattedCount > 0) {
        console.log(`    βœ… Formatted ${formattedCount} display math block(s) with proper spacing`);
    }

    return formattedContent;
}

/**
 * Clean newlines from figcaption content
 * @param {string} content - MDX content
 * @returns {string} - Content with cleaned figcaptions
 */
function cleanFigcaptionNewlines(content) {
    console.log('  πŸ“ Cleaning newlines in figcaption elements...');

    let cleanedCount = 0;

    // Find all <figcaption>...</figcaption> blocks and remove internal newlines
    const cleanedContent = content.replace(/<figcaption([^>]*)>([\s\S]*?)<\/figcaption>/g, (match, attributes, captionContent) => {
        // Only process if the content contains newlines
        if (captionContent.includes('\n')) {
            cleanedCount++;

            // Remove newlines and normalize whitespace
            const cleanedCaption = captionContent
                .replace(/\n+/g, ' ')           // Replace newlines with spaces
                .replace(/\s+/g, ' ')           // Normalize multiple spaces
                .trim();                        // Trim whitespace

            return `<figcaption${attributes}>${cleanedCaption}</figcaption>`;
        }

        return match; // Return unchanged if no newlines
    });

    if (cleanedCount > 0) {
        console.log(`    βœ… Cleaned ${cleanedCount} figcaption element(s)`);
    } else {
        console.log(`    ℹ️  No figcaption elements with newlines found`);
    }

    return cleanedContent;
}

/**
 * Remove HTML comments from MDX content
 * @param {string} content - MDX content
 * @returns {string} - Content without HTML comments
 */
function removeHtmlComments(content) {
    console.log('  πŸ—‘οΈ  Removing HTML comments...');

    let removedCount = 0;

    // Remove all HTML comments <!-- ... -->
    const cleanedContent = content.replace(/<!--[\s\S]*?-->/g, () => {
        removedCount++;
        return '';
    });

    if (removedCount > 0) {
        console.log(`    βœ… Removed ${removedCount} HTML comment(s)`);
    }

    return cleanedContent;
}

/**
 * Clean up MDX-incompatible syntax  
 * @param {string} content - MDX content
 * @returns {string} - Cleaned content
 */
function cleanMdxSyntax(content) {
    console.log('  🧹 Cleaning MDX syntax...');

    return content
        // NOTE: Math delimiter fixing is now handled by fixMixedMathDelimiters()
        // Ensure proper spacing around JSX-like constructs
        .replace(/>\s*</g, '>\n<')
        // Remove problematic heading attributes - be more specific to avoid matching \begin{align}
        .replace(/^(#{1,6}\s+[^{#\n]+)\{[^}]+\}$/gm, '$1')
        // Fix escaped quotes in text
        .replace(/\\("|')/g, '$1');
}

/**
 * Main MDX processing function that applies all transformations
 * @param {string} content - Raw Markdown content
 * @param {string} latexContent - Original LaTeX content for metadata extraction
 * @returns {string} - Processed MDX content compatible with Astro
 */
function processMdxContent(content, latexContent = '') {
    console.log('πŸ”§ Processing for Astro MDX compatibility...');

    // Clear previous tracking
    usedComponents.clear();
    imageImports.clear();

    let processedContent = content;

    // Apply each transformation step sequentially
    processedContent = ensureFrontmatter(processedContent, latexContent);
    processedContent = fixMixedMathDelimiters(processedContent);

    // Debug: check for $$ blocks after fixMixedMathDelimiters
    const mathBlocksAfterMixed = (processedContent.match(/\$\$([\s\S]*?)\$\$/g) || []).length;
    console.log(`    πŸ“Š Math blocks after mixed delimiters fix: ${mathBlocksAfterMixed}`);

    processedContent = cleanOrphanedMathDelimiters(processedContent);
    processedContent = cleanSingleLineMathNewlines(processedContent);
    processedContent = formatDisplayMathBlocks(processedContent);
    processedContent = removeHtmlComments(processedContent);
    processedContent = cleanMdxSyntax(processedContent);
    processedContent = convertSubfiguresToMultiImage(processedContent);
    processedContent = transformImages(processedContent);
    processedContent = transformImageFigures(processedContent);
    processedContent = transformStyledSpans(processedContent);
    processedContent = transformHighlightSpans(processedContent);
    processedContent = fixEscapedMarkTags(processedContent);
    processedContent = transformEpigraphs(processedContent);
    processedContent = transformReferenceLinks(processedContent);
    processedContent = fixHtmlEscaping(processedContent);
    processedContent = cleanHighlightNumbering(processedContent);
    processedContent = cleanFigcaptionNewlines(processedContent);

    // Add component imports at the end
    processedContent = addComponentImports(processedContent);

    return processedContent;
}

function convertToMdx(inputFile, outputFile) {
    console.log('πŸ“ Modular Markdown to Astro MDX Converter');
    console.log(`πŸ“ Input:  ${inputFile}`);
    console.log(`πŸ“ Output: ${outputFile}`);

    // Check if input file exists
    if (!existsSync(inputFile)) {
        console.error(`❌ Input file not found: ${inputFile}`);
        process.exit(1);
    }

    try {
        console.log('πŸ”„ Reading Markdown file...');
        const markdownContent = readFileSync(inputFile, 'utf8');

        // Try to read original LaTeX file for metadata extraction
        let latexContent = '';
        try {
            const inputDir = dirname(inputFile);
            const latexFile = join(inputDir, '..', 'input', 'main.tex');
            if (existsSync(latexFile)) {
                latexContent = readFileSync(latexFile, 'utf8');
            }
        } catch (error) {
            // Ignore LaTeX reading errors - we'll use fallback frontmatter
        }

        // Apply modular MDX processing
        const mdxContent = processMdxContent(markdownContent, latexContent);

        console.log('πŸ’Ύ Writing MDX file...');
        writeFileSync(outputFile, mdxContent);

        console.log(`βœ… Conversion completed: ${outputFile}`);

        // Show file size
        const inputSize = Math.round(markdownContent.length / 1024);
        const outputSize = Math.round(mdxContent.length / 1024);
        console.log(`πŸ“Š Input: ${inputSize}KB β†’ Output: ${outputSize}KB`);

    } catch (error) {
        console.error('❌ Conversion failed:');
        console.error(error.message);
        process.exit(1);
    }
}

export { convertToMdx };

function main() {
    const config = parseArgs();
    convertToMdx(config.input, config.output);
    console.log('πŸŽ‰ MDX conversion completed!');
}

if (import.meta.url === `file://${process.argv[1]}`) {
    main();
}