ctb_formats_pan/
output.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! Output parsed document.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35use std::collections::HashSet;
36use std::fs;
37use std::path::{Path, PathBuf};
38
39use crate::parser;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum PanCsvEncoding {
43    #[default]
44    Utf8,
45    Utf8Windows,
46    MacRoman,
47    Windows,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub enum PanExportDelimiter {
52    #[default]
53    Commas,
54    Tabs,
55    TabsWithoutQuotes,
56    WordPerfect,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct PanCsvOptions {
61    pub output_patterns: bool,
62    pub truncate_multiline: bool,
63    pub include_header: bool,
64    pub encoding: PanCsvEncoding,
65    pub delimiter: PanExportDelimiter,
66    pub crlf: bool,
67    pub replicate_double_encoding: bool,
68    pub run_startup_procedure: bool,
69}
70
71impl Default for PanCsvOptions {
72    fn default() -> Self {
73        Self {
74            output_patterns: false,
75            truncate_multiline: true,
76            include_header: true,
77            encoding: PanCsvEncoding::Utf8,
78            delimiter: PanExportDelimiter::Commas,
79            crlf: false,
80            replicate_double_encoding: false,
81            run_startup_procedure: false,
82        }
83    }
84}
85
86pub fn pan_to_csv(
87    pan_file: &[u8],
88    output_patterns: bool,
89) -> anyhow::Result<String> {
90    let options = PanCsvOptions {
91        output_patterns,
92        truncate_multiline: true,
93        include_header: true,
94        encoding: PanCsvEncoding::Utf8,
95        delimiter: PanExportDelimiter::Commas,
96        crlf: false,
97        replicate_double_encoding: false,
98        run_startup_procedure: false,
99    };
100    let bytes = pan_to_csv_with_options(pan_file, &options)?;
101    String::from_utf8(bytes).context("CSV output is not valid UTF-8")
102}
103
104pub fn pan_to_csv_with_options(
105    pan_file: &[u8],
106    options: &PanCsvOptions,
107) -> anyhow::Result<Vec<u8>> {
108    let pan = if options.run_startup_procedure {
109        let mut runtime =
110            crate::runtime::PanRuntimeState::from_pan_bytes(pan_file)?;
111        let report = runtime.run_startup_procedure()?;
112        for op in &report.pending_operations {
113            warn_fmt!("PAN startup pending operation: {op}");
114        }
115        runtime.document
116    } else {
117        parser::parse_pan(pan_file)?
118    };
119    let Some(schema) = pan.schema.as_ref() else {
120        warn!("PAN file does not contain schema/data records");
121        return Ok(Vec::new());
122    };
123    if schema.fields.is_empty() {
124        warn!("PAN file does not contain schema fields");
125        return Ok(Vec::new());
126    }
127    let Some(data) = pan.data.as_ref() else {
128        warn!("PAN file does not contain data section records");
129        return Ok(Vec::new());
130    };
131    for warning in &data.parse_warnings {
132        warn_fmt!("PAN parse warning: {warning}");
133    }
134
135    let header = if options.include_header {
136        Some(
137            schema
138                .fields
139                .iter()
140                .map(|field| {
141                    field
142                        .name
143                        .replace("\r\n", " ")
144                        .replace(['\r', '\n'], " ")
145                        .trim()
146                        .to_string()
147                })
148                .collect::<Vec<_>>(),
149        )
150    } else {
151        None
152    };
153
154    let mut rows = Vec::with_capacity(data.records.len());
155    for record in &data.records {
156        let mut row = Vec::with_capacity(record.fields.len());
157        for field in &record.fields {
158            let value = csv_field_bytes(field, options)?;
159            row.push(value);
160        }
161        rows.push(row);
162    }
163
164    Ok(write_csv_bytes(
165        header.as_deref(),
166        &rows,
167        options.crlf,
168        options.encoding,
169        options.delimiter,
170    ))
171}
172
173/// Convert a PAN file to JSON string. Mainly for testing and debugging
174/// purposes; don't expect this to be a stable output format.
175pub fn pan_to_parse_json(pan_file: &[u8]) -> anyhow::Result<String> {
176    let pan = parser::parse_pan(pan_file)?;
177    serde_json::to_string_pretty(&pan)
178        .context("Failed to serialize PAN document to JSON")
179}
180
181/// Read a PAN file from disk and return CSV bytes for stdout-style output.
182pub fn pan_file_to_csv_stdout(
183    pan_file: &Path,
184    output_patterns: bool,
185) -> anyhow::Result<Vec<u8>> {
186    let pan_data = fs::read(pan_file).with_context(|| {
187        format!(
188            "Could not read PAN file: {pan_file_display}",
189            pan_file_display = pan_file.display()
190        )
191    })?;
192    let options = PanCsvOptions {
193        output_patterns,
194        truncate_multiline: true,
195        include_header: true,
196        encoding: PanCsvEncoding::Utf8,
197        delimiter: PanExportDelimiter::Commas,
198        crlf: false,
199        replicate_double_encoding: false,
200        run_startup_procedure: false,
201    };
202    pan_to_csv_with_options(&pan_data, &options)
203}
204
205pub fn pan_file_to_csv_with_options_stdout(
206    pan_file: &Path,
207    options: &PanCsvOptions,
208) -> anyhow::Result<Vec<u8>> {
209    let pan_data = fs::read(pan_file).with_context(|| {
210        format!(
211            "Could not read PAN file: {pan_file_display}",
212            pan_file_display = pan_file.display()
213        )
214    })?;
215    pan_to_csv_with_options(&pan_data, options)
216}
217
218pub fn pan_file_to_parse_json_stdout(
219    pan_file: &Path,
220) -> anyhow::Result<Vec<u8>> {
221    let pan_data = fs::read(pan_file).with_context(|| {
222        format!(
223            "Could not read PAN file: {pan_file_display}",
224            pan_file_display = pan_file.display()
225        )
226    })?;
227    let json = pan_to_parse_json(&pan_data)?;
228    Ok(json.into_bytes())
229}
230
231/// Extract the source code of a specified macro by name using the requested encoding.
232pub fn pan_to_macro_with_encoding(
233    pan_file: &[u8],
234    macro_name: &str,
235    encoding: PanCsvEncoding,
236) -> anyhow::Result<String> {
237    let pan = parser::parse_pan(pan_file)?;
238    if let Some(macro_info) = pan.macros.iter().find(|m| m.name == macro_name) {
239        if let Some(raw) = macro_info.raw_code_bytes() {
240            return format_procedure_code(raw, encoding);
241        }
242        if let Some(ref code) = macro_info.code {
243            return Ok(code.clone());
244        }
245    }
246    bail!(
247        "Macro '{macro_name}' not found in PAN file (available macros: {:?})",
248        pan.macros.iter().map(|m| &m.name).collect::<Vec<_>>()
249    );
250}
251
252/// Extract the source code of a specified macro by name.
253pub fn pan_to_macro(
254    pan_file: &[u8],
255    macro_name: &str,
256) -> anyhow::Result<String> {
257    pan_to_macro_with_encoding(pan_file, macro_name, PanCsvEncoding::Windows)
258}
259
260/// Export all procedures from a PAN file into individual files within a folder.
261///
262/// If `output_dir` is not specified, creates a folder named `<stem>_procedures`
263/// alongside the PAN file (or in the current directory if input is from stdin).
264/// Errors if the target folder already exists.
265///
266/// Procedure names are sanitized with `ctb_io::file::clean_file_name` to
267/// ensure valid filenames and avoid overly long paths. Name collisions are
268/// disambiguated with numeric suffixes; if a unique filename cannot be found,
269/// returns an error.
270pub fn export_pan_procedures(
271    pan_file: &Path,
272    pan_data: &[u8],
273    output_dir: Option<&Path>,
274    extension: Option<&str>,
275    encoding: PanCsvEncoding,
276) -> anyhow::Result<String> {
277    let pan = parser::parse_pan(pan_data)?;
278
279    let target_dir = match output_dir {
280        Some(dir) => dir.to_path_buf(),
281        None => {
282            if pan_file.as_os_str() == "-" {
283                PathBuf::from("pan_procedures")
284            } else {
285                // Reason for fallback: when input file path has no valid stem or non-UTF8 name, defaults to "pan" folder prefix
286                let stem = pan_file
287                    .file_stem()
288                    .and_then(|s| s.to_str())
289                    .unwrap_or("pan");
290                let folder_name = format!("{stem}_procedures");
291                match pan_file.parent().filter(|p| !p.as_os_str().is_empty()) {
292                    Some(parent) => parent.join(folder_name),
293                    None => PathBuf::from(folder_name),
294                }
295            }
296        }
297    };
298
299    if target_dir.exists() {
300        bail!("Target directory already exists: {}", target_dir.display());
301    }
302
303    fs::create_dir_all(&target_dir).with_context(|| {
304        format!(
305            "Failed to create procedure export directory: {}",
306            target_dir.display()
307        )
308    })?;
309
310    let mut exported_count: usize = 0;
311    let mut seen_names: HashSet<String> = HashSet::new();
312
313    let ext_str = extension
314        .map(|e| e.trim_start_matches('.'))
315        .filter(|e| !e.is_empty());
316
317    for macro_info in &pan.macros {
318        let code = if let Some(raw) = macro_info.raw_code_bytes() {
319            format_procedure_code(raw, encoding)?
320        } else if let Some(ref c) = macro_info.code {
321            c.clone()
322        } else {
323            String::new()
324        };
325
326        let clean_stem =
327            ctb_io::file::clean_file_name(&macro_info.name, Some(&target_dir));
328        let base_name = clean_stem.to_string_lossy();
329        let base_name = if base_name.is_empty() {
330            "unnamed"
331        } else {
332            &base_name
333        };
334
335        let initial_candidate = match ext_str {
336            Some(ext) => format!("{base_name}.{ext}"),
337            None => base_name.to_string(),
338        };
339
340        let mut final_filename = None;
341        if !seen_names.contains(&initial_candidate)
342            && !target_dir.join(&initial_candidate).exists()
343        {
344            final_filename = Some(initial_candidate);
345        } else {
346            let mut suffix: usize = 2;
347            while suffix <= 1000 {
348                let candidate = match ext_str {
349                    Some(ext) => format!("{base_name}_{suffix}.{ext}"),
350                    None => format!("{base_name}_{suffix}"),
351                };
352                if candidate.len() <= ctb_io::file::MAX_FILENAME_BYTES
353                    && !seen_names.contains(&candidate)
354                    && !target_dir.join(&candidate).exists()
355                {
356                    final_filename = Some(candidate);
357                    break;
358                }
359                suffix = suffix.saturating_add(1);
360            }
361        }
362
363        let Some(filename) = final_filename else {
364            bail!(
365                "Cannot find a usable unique filename for procedure '{}' in {}",
366                macro_info.name,
367                target_dir.display()
368            );
369        };
370
371        seen_names.insert(filename.clone());
372        let file_path = target_dir.join(&filename);
373        fs::write(&file_path, code.as_bytes()).with_context(|| {
374            format!("Failed to write procedure file: {}", file_path.display())
375        })?;
376        exported_count = exported_count.saturating_add(1);
377    }
378
379    Ok(format!(
380        "Exported {exported_count} procedure(s) to {}\n",
381        target_dir.display()
382    ))
383}
384
385/// Read a PAN file from disk and return macro procedure code bytes for stdout.
386pub fn pan_file_to_macro_with_encoding_stdout(
387    pan_file: &Path,
388    macro_name: &str,
389    encoding: PanCsvEncoding,
390) -> anyhow::Result<Vec<u8>> {
391    let pan_data = fs::read(pan_file).with_context(|| {
392        format!(
393            "Could not read PAN file: {pan_file_display}",
394            pan_file_display = pan_file.display()
395        )
396    })?;
397    let macro_code =
398        pan_to_macro_with_encoding(&pan_data, macro_name, encoding)?;
399    Ok(macro_code.into_bytes())
400}
401
402/// Read a PAN file from disk and return macro procedure code bytes for stdout.
403pub fn pan_file_to_macro_stdout(
404    pan_file: &Path,
405    macro_name: &str,
406) -> anyhow::Result<Vec<u8>> {
407    pan_file_to_macro_with_encoding_stdout(
408        pan_file,
409        macro_name,
410        PanCsvEncoding::Windows,
411    )
412}
413
414/// Parse a macro procedure into AST JSON string.
415/// If `macro_name` is Some, `input_bytes` is treated as a PAN database file.
416/// If `macro_name` is None, `input_bytes` is treated directly as macro procedure code.
417pub fn panmacro_to_ast_json(
418    input_bytes: &[u8],
419    macro_name: Option<&str>,
420    input_encoding: PanCsvEncoding,
421) -> anyhow::Result<String> {
422    let macro_code = if let Some(name) = macro_name {
423        pan_to_macro_with_encoding(input_bytes, name, input_encoding)?
424    } else {
425        format_procedure_code(input_bytes, input_encoding)?
426    };
427
428    let ast = crate::procedure_parser::parse_procedure(&macro_code)?;
429    serde_json::to_string_pretty(&ast)
430        .context("Failed to serialize procedure AST to JSON")
431}
432
433/// Encode an AST JSON string into bytes using the requested output encoding.
434pub fn encode_ast_json_output(
435    ast_json: &str,
436    output_encoding: PanCsvEncoding,
437) -> anyhow::Result<Vec<u8>> {
438    match output_encoding {
439        PanCsvEncoding::Windows => ctb_formats_encoding::encode(
440            ctb_formats_encoding::CharEncoding::windows_1252(),
441            ast_json,
442        ),
443        PanCsvEncoding::MacRoman => ctb_formats_encoding::encode(
444            ctb_formats_encoding::CharEncoding::mac_roman(),
445            ast_json,
446        ),
447        PanCsvEncoding::Utf8 | PanCsvEncoding::Utf8Windows => {
448            Ok(ast_json.as_bytes().to_vec())
449        }
450    }
451}
452
453/// Extract and parse a macro/procedure into an AST JSON string.
454pub fn pan_to_ast_with_encoding(
455    pan_file: &[u8],
456    macro_name: &str,
457    encoding: PanCsvEncoding,
458) -> anyhow::Result<String> {
459    panmacro_to_ast_json(pan_file, Some(macro_name), encoding)
460}
461
462/// Extract and parse a macro/procedure into an AST JSON string.
463pub fn pan_to_ast(pan_file: &[u8], macro_name: &str) -> anyhow::Result<String> {
464    pan_to_ast_with_encoding(pan_file, macro_name, PanCsvEncoding::Windows)
465}
466
467/// Read a PAN file from disk and return AST JSON bytes for stdout.
468pub fn pan_file_to_ast_with_encoding_stdout(
469    pan_file: &Path,
470    macro_name: &str,
471    encoding: PanCsvEncoding,
472) -> anyhow::Result<Vec<u8>> {
473    let pan_data = fs::read(pan_file).with_context(|| {
474        format!(
475            "Could not read PAN file: {pan_file_display}",
476            pan_file_display = pan_file.display()
477        )
478    })?;
479    let ast_json = pan_to_ast_with_encoding(&pan_data, macro_name, encoding)?;
480    Ok(ast_json.into_bytes())
481}
482
483/// Read a PAN file from disk and return AST JSON bytes for stdout.
484pub fn pan_file_to_ast_stdout(
485    pan_file: &Path,
486    macro_name: &str,
487) -> anyhow::Result<Vec<u8>> {
488    pan_file_to_ast_with_encoding_stdout(
489        pan_file,
490        macro_name,
491        PanCsvEncoding::Windows,
492    )
493}
494
495fn format_procedure_code(
496    input_bytes: &[u8],
497    encoding: PanCsvEncoding,
498) -> anyhow::Result<String> {
499    let decoded = match encoding {
500        PanCsvEncoding::Utf8 => String::from_utf8(input_bytes.to_vec())
501            .context("Procedure code is not valid UTF-8")?,
502        PanCsvEncoding::Utf8Windows | PanCsvEncoding::Windows => {
503            ctb_formats_encoding::altura::mac_roman_to_utf8_windows(
504                input_bytes,
505            )?
506        }
507        PanCsvEncoding::MacRoman => ctb_formats_encoding::decode(
508            ctb_formats_encoding::CharEncoding::mac_roman(),
509            input_bytes,
510        )?,
511    };
512
513    let mut result = String::new();
514    for line in decoded.split('\r') {
515        result.push_str(line.trim_end());
516        result.push('\n');
517    }
518    Ok(result)
519}
520
521fn csv_field_bytes(
522    field: &parser::PanDataFieldValue,
523    options: &PanCsvOptions,
524) -> anyhow::Result<Vec<u8>> {
525    match &field.value {
526        parser::PanDataValue::Text(text) => {
527            let is_tabs_no_quotes =
528                options.delimiter == PanExportDelimiter::TabsWithoutQuotes;
529            if options.encoding == PanCsvEncoding::Windows {
530                let double_pass = options.replicate_double_encoding;
531                let mut mapped = field
532                    .raw_bytes
533                    .iter()
534                    .map(|&b| {
535                        let b1 = ctb_formats_encoding::altura::mac_roman_to_ansi_byte(b);
536                        if double_pass && b != 0xfe && b != 0xff {
537                            ctb_formats_encoding::altura::mac_roman_to_ansi_byte(b1)
538                        } else {
539                            b1
540                        }
541                    })
542                    .collect::<Vec<u8>>();
543                if options.output_patterns && options.truncate_multiline {
544                    if let Some(pos) =
545                        mapped.iter().position(|&b| b == b'\r' || b == b'\n')
546                    {
547                        mapped.truncate(pos);
548                    }
549                } else if is_tabs_no_quotes {
550                    for b in &mut mapped {
551                        if *b == b'\r' {
552                            *b = 0x0b;
553                        }
554                    }
555                } else if options.delimiter == PanExportDelimiter::WordPerfect {
556                    for b in &mut mapped {
557                        if *b == 0x0b {
558                            *b = b'\r';
559                        }
560                    }
561                }
562                Ok(mapped)
563            } else if options.encoding == PanCsvEncoding::Utf8Windows {
564                let decoded =
565                    ctb_formats_encoding::altura::mac_roman_to_utf8_windows(
566                        &field.raw_bytes,
567                    )?;
568                let mut mapped = decoded.into_bytes();
569                if options.output_patterns && options.truncate_multiline {
570                    if let Some(pos) =
571                        mapped.iter().position(|&b| b == b'\r' || b == b'\n')
572                    {
573                        mapped.truncate(pos);
574                    }
575                } else if is_tabs_no_quotes {
576                    for b in &mut mapped {
577                        if *b == b'\r' {
578                            *b = 0x0b;
579                        }
580                    }
581                } else if options.delimiter == PanExportDelimiter::WordPerfect {
582                    for b in &mut mapped {
583                        if *b == 0x0b {
584                            *b = b'\r';
585                        }
586                    }
587                }
588                Ok(mapped)
589            } else if options.encoding == PanCsvEncoding::MacRoman {
590                let mut raw = field.raw_bytes.clone();
591                if options.output_patterns && options.truncate_multiline {
592                    if let Some(pos) =
593                        raw.iter().position(|&b| b == b'\r' || b == b'\n')
594                    {
595                        raw.truncate(pos);
596                    }
597                }
598                Ok(raw)
599            } else if options.output_patterns && options.truncate_multiline {
600                let first_line = text
601                    .split(['\r', '\n'])
602                    .next()
603                    // Reason for fallback: split always yields at least one item
604                    .unwrap_or("");
605                Ok(first_line.as_bytes().to_vec())
606            } else if is_tabs_no_quotes {
607                let replaced =
608                    text.replace("\r\n", "\x0b\n").replace('\r', "\x0b");
609                Ok(replaced.into_bytes())
610            } else if options.delimiter == PanExportDelimiter::WordPerfect {
611                let norm = text.replace('\x0b', "\r");
612                Ok(norm.into_bytes())
613            } else {
614                Ok(text.as_bytes().to_vec())
615            }
616        }
617        parser::PanDataValue::Integer(integer) => {
618            if options.output_patterns {
619                if let Some(formatted) = field.formatted_value.as_ref() {
620                    return Ok(formatted.as_bytes().to_vec());
621                }
622            }
623            if options.encoding == PanCsvEncoding::MacRoman
624                && integer.is_empty()
625            {
626                return Ok(b"0".to_vec());
627            }
628            Ok(integer.as_bytes().to_vec())
629        }
630        parser::PanDataValue::Fixed(fixed) => {
631            if options.output_patterns {
632                if let Some(formatted) = field.formatted_value.as_ref() {
633                    return Ok(formatted.as_bytes().to_vec());
634                }
635            }
636            if options.encoding == PanCsvEncoding::MacRoman && fixed.is_empty()
637            {
638                return Ok(b"0".to_vec());
639            }
640            Ok(fixed.as_bytes().to_vec())
641        }
642        parser::PanDataValue::Float(float_value) => {
643            if options.output_patterns {
644                if let Some(formatted) = field.formatted_value.as_ref() {
645                    return Ok(formatted.as_bytes().to_vec());
646                }
647            }
648            Ok(float_value.as_bytes().to_vec())
649        }
650        parser::PanDataValue::Date {
651            raw_serial,
652            pan_date_mdy,
653        } => {
654            if *raw_serial == 0 {
655                Ok(Vec::new())
656            } else if options.output_patterns {
657                if let Some(formatted) = field.formatted_value.as_ref() {
658                    Ok(formatted.as_bytes().to_vec())
659                } else if options.encoding == PanCsvEncoding::Windows
660                    || options.encoding == PanCsvEncoding::Utf8Windows
661                {
662                    if let Ok(formatted) =
663                        crate::date::datepattern(*raw_serial, "MM/DD/YYYY")
664                    {
665                        Ok(formatted.into_bytes())
666                    } else if let Some(mdy) = pan_date_mdy.as_deref() {
667                        Ok(mdy.as_bytes().to_vec())
668                    } else {
669                        Ok(Vec::new())
670                    }
671                } else if let Ok(formatted) =
672                    crate::date::datepattern(*raw_serial, "MM/DD/yy")
673                {
674                    Ok(formatted.into_bytes())
675                } else if let Some(mdy) = pan_date_mdy.as_deref() {
676                    Ok(mdy.as_bytes().to_vec())
677                } else {
678                    Ok(Vec::new())
679                }
680            } else if options.encoding == PanCsvEncoding::Windows
681                || options.encoding == PanCsvEncoding::Utf8Windows
682            {
683                if let Ok(formatted) =
684                    crate::date::datepattern(*raw_serial, "MM/DD/YYYY")
685                {
686                    Ok(formatted.into_bytes())
687                } else if let Some(mdy) = pan_date_mdy.as_deref() {
688                    Ok(mdy.as_bytes().to_vec())
689                } else {
690                    Ok(Vec::new())
691                }
692            } else if let Ok(formatted) =
693                crate::date::datepattern(*raw_serial, "MM/DD/yy")
694            {
695                Ok(formatted.into_bytes())
696            } else if let Some(mdy) = pan_date_mdy.as_deref() {
697                Ok(mdy.as_bytes().to_vec())
698            } else {
699                Ok(Vec::new())
700            }
701        }
702        parser::PanDataValue::Unknown(value) => Ok(value.as_bytes().to_vec()),
703    }
704}
705
706fn format_export_cell(
707    cell_bytes: &[u8],
708    delimiter: PanExportDelimiter,
709) -> Vec<u8> {
710    match delimiter {
711        PanExportDelimiter::Commas => {
712            let needs_quote = cell_bytes.iter().any(|&b| {
713                b == b',' || b == b'"' || b == b'\r' || b == b'\n' || b == b'\t'
714            });
715            if needs_quote {
716                let mut out =
717                    Vec::with_capacity(cell_bytes.len().saturating_add(2));
718                out.push(b'"');
719                for &b in cell_bytes {
720                    if b == b'"' {
721                        out.push(b'"');
722                        out.push(b'"');
723                    } else {
724                        out.push(b);
725                    }
726                }
727                out.push(b'"');
728                out
729            } else {
730                cell_bytes.to_vec()
731            }
732        }
733        PanExportDelimiter::Tabs => {
734            let needs_quote = cell_bytes.iter().any(|&b| {
735                b == b',' || b == b'\t' || b == b'"' || b == b'\r' || b == b'\n'
736            });
737            if needs_quote {
738                let mut out =
739                    Vec::with_capacity(cell_bytes.len().saturating_add(2));
740                out.push(b'"');
741                for &b in cell_bytes {
742                    if b == b'"' {
743                        out.push(b'"');
744                        out.push(b'"');
745                    } else {
746                        out.push(b);
747                    }
748                }
749                out.push(b'"');
750                out
751            } else {
752                cell_bytes.to_vec()
753            }
754        }
755        PanExportDelimiter::TabsWithoutQuotes
756        | PanExportDelimiter::WordPerfect => cell_bytes.to_vec(),
757    }
758}
759
760fn write_csv_bytes(
761    header: Option<&[String]>,
762    rows: &[Vec<Vec<u8>>],
763    crlf: bool,
764    encoding: PanCsvEncoding,
765    delimiter: PanExportDelimiter,
766) -> Vec<u8> {
767    let line_ending = if crlf || encoding == PanCsvEncoding::Windows {
768        b"\r\n".as_slice()
769    } else if encoding == PanCsvEncoding::MacRoman {
770        b"\r".as_slice()
771    } else {
772        b"\n".as_slice()
773    };
774
775    let mut out = Vec::new();
776    match delimiter {
777        PanExportDelimiter::Commas => {
778            if let Some(header_fields) = header {
779                let mut header_cells = Vec::with_capacity(header_fields.len());
780                for name in header_fields {
781                    header_cells
782                        .push(format_export_cell(name.as_bytes(), delimiter));
783                }
784                out.extend(header_cells.join(&b","[..]));
785                out.extend_from_slice(line_ending);
786            }
787
788            for row in rows {
789                let mut row_cells = Vec::with_capacity(row.len());
790                for cell in row {
791                    row_cells.push(format_export_cell(cell, delimiter));
792                }
793                out.extend(row_cells.join(&b","[..]));
794                out.extend_from_slice(line_ending);
795            }
796        }
797        PanExportDelimiter::Tabs | PanExportDelimiter::TabsWithoutQuotes => {
798            if let Some(header_fields) = header {
799                let mut header_cells = Vec::with_capacity(header_fields.len());
800                for name in header_fields {
801                    header_cells
802                        .push(format_export_cell(name.as_bytes(), delimiter));
803                }
804                out.extend(header_cells.join(&b"\t"[..]));
805                out.extend_from_slice(line_ending);
806            }
807
808            for row in rows {
809                let mut row_cells = Vec::with_capacity(row.len());
810                for cell in row {
811                    row_cells.push(format_export_cell(cell, delimiter));
812                }
813                out.extend(row_cells.join(&b"\t"[..]));
814                out.extend_from_slice(line_ending);
815            }
816        }
817        PanExportDelimiter::WordPerfect => {
818            let wp_field_sep = if crlf {
819                b"\x12\r\n".as_slice()
820            } else {
821                b"\x12\n".as_slice()
822            };
823            let wp_record_sep = if crlf {
824                b"\x05\r\n".as_slice()
825            } else {
826                b"\x05\n".as_slice()
827            };
828
829            if let Some(header_fields) = header {
830                let mut header_cells = Vec::with_capacity(header_fields.len());
831                for name in header_fields {
832                    header_cells.push(name.as_bytes().to_vec());
833                }
834                out.extend(header_cells.join(wp_field_sep));
835                out.extend_from_slice(wp_record_sep);
836            }
837
838            for row in rows {
839                for cell in row {
840                    out.extend_from_slice(cell);
841                    out.extend_from_slice(wp_field_sep);
842                }
843                out.extend_from_slice(wp_record_sep);
844            }
845        }
846    }
847
848    out
849}
850
851#[cfg(test)]
852#[allow(
853    clippy::panic,
854    clippy::expect_used,
855    clippy::unwrap_used,
856    clippy::unwrap_in_result,
857    clippy::panic_in_result_fn,
858    clippy::indexing_slicing,
859    clippy::arithmetic_side_effects,
860    reason = "Standard repository test boilerplate"
861)]
862mod tests {
863    use ctb_utilities::anyhow::ensure;
864
865    use super::*;
866
867    #[crate::ctb_test]
868    fn test_pan_to_csv_matches_expected_output() -> anyhow::Result<()> {
869        let pan = crate::get_pan_data("fixtures/SAMPLE.pan")
870            .context("Could not load fixtures/SAMPLE.pan")?;
871        let expected_csv =
872            crate::get_pan_data("fixtures/SAMPLE.pan.expected-out.csv")
873                .context(
874                    "Could not load fixtures/SAMPLE.pan.expected-out.csv",
875                )?;
876
877        let expected_csv = String::from_utf8(expected_csv)
878            .context("Expected CSV fixture is not valid UTF-8")?;
879        let actual_csv = pan_to_csv(&pan, false)?;
880
881        ensure!(
882            actual_csv == expected_csv,
883            "Actual CSV output does not match expected output: \nActual:\n{actual_csv}\nExpected:\n{expected_csv}"
884        );
885        Ok(())
886    }
887
888    #[crate::ctb_test]
889    fn test_pan_to_csv_output_patterns_toggle() -> anyhow::Result<()> {
890        let pan = crate::get_pan_data("fixtures/Sample with patterns.pan")
891            .context("Could not load fixtures/Sample with patterns.pan")?;
892
893        let raw_csv = pan_to_csv(&pan, false)?;
894        let patterned_csv = pan_to_csv(&pan, true)?;
895
896        ensure!(raw_csv != patterned_csv);
897        ensure!(raw_csv.contains(",1.11,"));
898        ensure!(patterned_csv.contains(",1.11 oz,"));
899        ensure!(raw_csv.contains(",05/03/35,"));
900        ensure!(patterned_csv.contains(",05-03-1935,"));
901
902        Ok(())
903    }
904
905    #[crate::ctb_test]
906    fn test_pan_to_parse_json_contains_schema_and_data() -> anyhow::Result<()> {
907        let pan = crate::get_pan_data("fixtures/SAMPLE.pan")
908            .context("Could not load fixtures/SAMPLE.pan")?;
909
910        let json_output = pan_to_parse_json(&pan)?;
911        let parsed: serde_json::Value = serde_json::from_str(&json_output)
912            .context("JSON output is not valid JSON")?;
913
914        ensure!(parsed.get("schema").is_some());
915        ensure!(parsed.get("data").is_some());
916
917        Ok(())
918    }
919
920    #[crate::ctb_test]
921    fn test_write_csv_string_escapes_quotes_and_newlines() -> anyhow::Result<()>
922    {
923        let header = vec!["Name".to_string(), "Notes".to_string()];
924        let rows =
925            vec![vec![b"Alice \"A\"".to_vec(), b"line1\nline2".to_vec()]];
926
927        let csv_bytes = write_csv_bytes(
928            Some(&header),
929            &rows,
930            false,
931            PanCsvEncoding::Utf8,
932            PanExportDelimiter::Commas,
933        );
934        let csv_output = String::from_utf8(csv_bytes)?;
935        ensure!(
936            csv_output == "Name,Notes\n\"Alice \"\"A\"\"\",\"line1\nline2\"\n"
937        );
938
939        Ok(())
940    }
941
942    #[crate::ctb_test]
943    fn test_pan_csv_options_header_toggle() -> anyhow::Result<()> {
944        let pan = crate::get_pan_data("fixtures/SAMPLE.pan")
945            .context("Could not load fixtures/SAMPLE.pan")?;
946
947        let with_header = pan_to_csv_with_options(
948            &pan,
949            &PanCsvOptions {
950                output_patterns: false,
951                truncate_multiline: true,
952                include_header: true,
953                encoding: PanCsvEncoding::Utf8,
954                delimiter: PanExportDelimiter::Commas,
955                crlf: false,
956                replicate_double_encoding: false,
957                run_startup_procedure: false,
958            },
959        )?;
960        let no_header = pan_to_csv_with_options(
961            &pan,
962            &PanCsvOptions {
963                output_patterns: false,
964                truncate_multiline: true,
965                include_header: false,
966                encoding: PanCsvEncoding::Utf8,
967                delimiter: PanExportDelimiter::Commas,
968                crlf: false,
969                replicate_double_encoding: false,
970                run_startup_procedure: false,
971            },
972        )?;
973
974        let with_header_str = String::from_utf8(with_header)?;
975        let no_header_str = String::from_utf8(no_header)?;
976
977        ensure!(
978            with_header_str
979                .starts_with("ExampleTextField,ExampleNumericFieldInt")
980        );
981        ensure!(
982            !no_header_str
983                .starts_with("ExampleTextField,ExampleNumericFieldInt")
984        );
985
986        Ok(())
987    }
988
989    #[crate::ctb_test]
990    fn test_pan_export_delimiters() -> anyhow::Result<()> {
991        let header = vec!["Name".to_string(), "City".to_string()];
992        let rows = vec![vec![b"Alice\tSmith".to_vec(), b"New York".to_vec()]];
993
994        let tsv = write_csv_bytes(
995            Some(&header),
996            &rows,
997            false,
998            PanCsvEncoding::Utf8,
999            PanExportDelimiter::Tabs,
1000        );
1001        ensure!(
1002            String::from_utf8(tsv)?
1003                == "Name\tCity\n\"Alice\tSmith\"\tNew York\n"
1004        );
1005
1006        let tsv_noq = write_csv_bytes(
1007            Some(&header),
1008            &rows,
1009            false,
1010            PanCsvEncoding::Utf8,
1011            PanExportDelimiter::TabsWithoutQuotes,
1012        );
1013        ensure!(
1014            String::from_utf8(tsv_noq)?
1015                == "Name\tCity\nAlice\tSmith\tNew York\n"
1016        );
1017
1018        let wp = write_csv_bytes(
1019            Some(&header),
1020            &rows,
1021            false,
1022            PanCsvEncoding::Utf8,
1023            PanExportDelimiter::WordPerfect,
1024        );
1025        ensure!(
1026            String::from_utf8(wp)?
1027                == "Name\x12\nCity\x05\nAlice\tSmith\x12\nNew York\x12\n\x05\n"
1028        );
1029
1030        Ok(())
1031    }
1032
1033    #[crate::ctb_test]
1034    fn test_pan_csv_keep_multiline_toggle() -> anyhow::Result<()> {
1035        let sample_csv_with_trunc = pan_to_csv_with_options(
1036            &crate::get_pan_data("fixtures/SAMPLE.pan")
1037                .context("Could not load fixtures/SAMPLE.pan")?,
1038            &PanCsvOptions {
1039                output_patterns: true,
1040                truncate_multiline: true,
1041                ..Default::default()
1042            },
1043        )?;
1044        let sample_csv_no_trunc = pan_to_csv_with_options(
1045            &crate::get_pan_data("fixtures/SAMPLE.pan")
1046                .context("Could not load fixtures/SAMPLE.pan")?,
1047            &PanCsvOptions {
1048                output_patterns: true,
1049                truncate_multiline: false,
1050                ..Default::default()
1051            },
1052        )?;
1053        ensure!(!sample_csv_with_trunc.is_empty());
1054        ensure!(!sample_csv_no_trunc.is_empty());
1055        Ok(())
1056    }
1057
1058    #[crate::ctb_test]
1059    fn test_sample_windows_export_fixtures_all_variants() -> anyhow::Result<()>
1060    {
1061        let pan_data = crate::get_pan_data("fixtures/SAMPLE.pan")
1062            .context("Could not load fixtures/SAMPLE.pan")?;
1063
1064        let delimiters = [
1065            ("commas", PanExportDelimiter::Commas),
1066            ("tabs", PanExportDelimiter::Tabs),
1067            ("tabs-no-quotes", PanExportDelimiter::TabsWithoutQuotes),
1068            ("wordperfect", PanExportDelimiter::WordPerfect),
1069        ];
1070
1071        for (delim_name, delim) in delimiters {
1072            for header in [true, false] {
1073                for patterns in [true, false] {
1074                    let header_slug = if header {
1075                        "field-names"
1076                    } else {
1077                        "no-field-names"
1078                    };
1079                    let patterns_slug = if patterns {
1080                        "output-patterns"
1081                    } else {
1082                        "no-output-patterns"
1083                    };
1084                    let fixture_name = format!(
1085                        "fixtures/SAMPLE-windows-{delim_name}-{header_slug}-{patterns_slug}.txt"
1086                    );
1087                    let expected = crate::get_pan_data(&fixture_name)
1088                        .with_context(|| {
1089                            format!("Could not load {fixture_name}")
1090                        })?;
1091
1092                    let options = PanCsvOptions {
1093                        include_header: header,
1094                        output_patterns: patterns,
1095                        truncate_multiline: true,
1096                        encoding: PanCsvEncoding::Windows,
1097                        crlf: delim != PanExportDelimiter::WordPerfect,
1098                        delimiter: delim,
1099                        replicate_double_encoding: false,
1100                        run_startup_procedure: false,
1101                    };
1102
1103                    let actual = pan_to_csv_with_options(&pan_data, &options)?;
1104                    ensure!(
1105                        actual == expected,
1106                        "Fixture mismatch for {fixture_name}: actual len {} vs expected len {}",
1107                        actual.len(),
1108                        expected.len()
1109                    );
1110                }
1111            }
1112        }
1113        Ok(())
1114    }
1115
1116    #[crate::ctb_test]
1117    fn test_sample_with_patterns_v2_export_fixtures_all_variants()
1118    -> anyhow::Result<()> {
1119        let pan_data =
1120            crate::get_pan_data("fixtures/Sample with patterns v2.pan")
1121                .context(
1122                    "Could not load fixtures/Sample with patterns v2.pan",
1123                )?;
1124
1125        let delimiters = [
1126            ("commas", "commas", PanExportDelimiter::Commas),
1127            ("tabs", "tabs", PanExportDelimiter::Tabs),
1128            (
1129                "tabs no quotes",
1130                "tabs no quotes",
1131                PanExportDelimiter::TabsWithoutQuotes,
1132            ),
1133            (
1134                "WordPerfect",
1135                "WordPerfect",
1136                PanExportDelimiter::WordPerfect,
1137            ),
1138        ];
1139
1140        for (_, delim_label, delim) in delimiters {
1141            for header in [true, false] {
1142                for patterns in [true, false] {
1143                    let header_slug = if header {
1144                        "field names"
1145                    } else {
1146                        "no field names"
1147                    };
1148                    let patterns_slug = if patterns {
1149                        "output patterns"
1150                    } else {
1151                        "no output patterns"
1152                    };
1153                    let fixture_name = format!(
1154                        "fixtures/Sample with patterns v2 Windows, {delim_label}, {header_slug}, {patterns_slug}.txt"
1155                    );
1156                    let expected = crate::get_pan_data(&fixture_name)
1157                        .with_context(|| {
1158                            format!("Could not load {fixture_name}")
1159                        })?;
1160
1161                    let options = PanCsvOptions {
1162                        include_header: header,
1163                        output_patterns: patterns,
1164                        truncate_multiline: true,
1165                        encoding: PanCsvEncoding::Windows,
1166                        crlf: delim != PanExportDelimiter::WordPerfect,
1167                        delimiter: delim,
1168                        replicate_double_encoding: false,
1169                        run_startup_procedure: false,
1170                    };
1171
1172                    let actual = pan_to_csv_with_options(&pan_data, &options)?;
1173                    ensure!(
1174                        actual == expected,
1175                        "Fixture mismatch for {fixture_name}: actual len {} vs expected len {}",
1176                        actual.len(),
1177                        expected.len()
1178                    );
1179                }
1180            }
1181        }
1182        Ok(())
1183    }
1184
1185    #[crate::ctb_test]
1186    fn test_pan_to_csv_header_normalizes_newlines() -> anyhow::Result<()> {
1187        let sample_bytes = crate::get_pan_data("fixtures/SAMPLE.pan")
1188            .context("Could not load fixtures/SAMPLE.pan")?;
1189        let options = PanCsvOptions {
1190            include_header: true,
1191            output_patterns: false,
1192            truncate_multiline: true,
1193            encoding: PanCsvEncoding::Utf8,
1194            delimiter: PanExportDelimiter::Commas,
1195            crlf: false,
1196            replicate_double_encoding: false,
1197            run_startup_procedure: false,
1198        };
1199        let csv_output = pan_to_csv_with_options(&sample_bytes, &options)?;
1200        let first_line = csv_output
1201            .split(|&b| b == b'\n')
1202            .next()
1203            .context("Empty CSV output")?;
1204        let header_str = std::str::from_utf8(first_line)?;
1205        ensure!(!header_str.contains('\r'));
1206        ensure!(
1207            header_str.starts_with("ExampleTextField,ExampleNumericFieldInt")
1208        );
1209        Ok(())
1210    }
1211
1212    #[crate::ctb_test]
1213    fn test_windows_export_tag_delimiters_single_pass() -> anyhow::Result<()> {
1214        let field = parser::PanDataFieldValue {
1215            field_index: 0,
1216            field_name: "TagField".to_string(),
1217            field_type: parser::PanFieldType::Text,
1218            type_label: "Text".to_string(),
1219            output_pattern: None,
1220            formula: None,
1221            raw_bytes: vec![0xfe, b'T', b'A', b'G', 0xff],
1222            value: parser::PanDataValue::Text("test".to_string()),
1223            formatted_value: None,
1224        };
1225        let options = PanCsvOptions {
1226            encoding: PanCsvEncoding::Windows,
1227            replicate_double_encoding: true,
1228            ..Default::default()
1229        };
1230        let result = csv_field_bytes(&field, &options)?;
1231        ensure!(result == vec![0xf0, b'T', b'A', b'G', 0xb9]);
1232        Ok(())
1233    }
1234
1235    #[crate::ctb_test]
1236    fn test_pan_to_macro_extracts_macro_code() -> anyhow::Result<()> {
1237        let mut pan_bytes = Vec::new();
1238        pan_bytes.extend_from_slice(&0u32.to_le_bytes());
1239        // Prelude entry
1240        pan_bytes.push(0x00);
1241        pan_bytes.push(4);
1242        pan_bytes.extend_from_slice(b"TEST");
1243        pan_bytes.push(0);
1244        pan_bytes.extend_from_slice(&0u32.to_le_bytes());
1245        // Section: size = 37, kind = 0x83, len = 6, name = "MACROS"
1246        pan_bytes.extend_from_slice(&37u32.to_le_bytes());
1247        pan_bytes.push(0x83);
1248        pan_bytes.push(6);
1249        pan_bytes.extend_from_slice(b"MACROS");
1250        // Macro record: size = 25, marker = 0x84, name_len = 5, name = "TestM"
1251        pan_bytes.extend_from_slice(&25u32.to_le_bytes());
1252        pan_bytes.push(0x84);
1253        pan_bytes.push(5);
1254        pan_bytes.extend_from_slice(b"TestM");
1255        pan_bytes.extend_from_slice(&12u16.to_le_bytes());
1256        pan_bytes.extend_from_slice(b"message \"Hi\"");
1257
1258        let code = pan_to_macro(&pan_bytes, "TestM")?;
1259        ensure!(code == "message \"Hi\"\n");
1260        Ok(())
1261    }
1262
1263    #[crate::ctb_test]
1264    fn test_pan_to_macro_extracts_locked_macro_code() -> anyhow::Result<()> {
1265        let mut pan_bytes = Vec::new();
1266        pan_bytes.extend_from_slice(&0u32.to_le_bytes());
1267        // Prelude entry
1268        pan_bytes.push(0x00);
1269        pan_bytes.push(4);
1270        pan_bytes.extend_from_slice(b"TEST");
1271        pan_bytes.push(0);
1272        pan_bytes.extend_from_slice(&0u32.to_le_bytes());
1273
1274        // Build locked macro record
1275        let name = b".LockedProc";
1276        let code_bytes = b"message \"Hello Locked\"";
1277        let code_len = u16::try_from(code_bytes.len())?;
1278
1279        // Plain body: [prefix 2 bytes] [bytecode 6 bytes] [code_len 2 bytes] [code]
1280        let mut unobfuscated_stream = Vec::new();
1281        unobfuscated_stream
1282            .extend_from_slice(&[0xff, 0xec, 0x00, 0x00, 0x00, 0x00]);
1283        unobfuscated_stream.extend_from_slice(&code_len.to_be_bytes());
1284        unobfuscated_stream.extend_from_slice(code_bytes);
1285
1286        // Obfuscate the stream with key = ((i + 2) * 3) & 0xFF
1287        let mut obfuscated_stream = Vec::new();
1288        for (idx, &b) in unobfuscated_stream.iter().enumerate() {
1289            let idx_u8 = u8::try_from(idx & 0xff).unwrap_or(0);
1290            let key = idx_u8.wrapping_add(2).wrapping_mul(3);
1291            obfuscated_stream.push(b ^ key);
1292        }
1293
1294        let mut macro_body = Vec::new();
1295        macro_body.extend_from_slice(&[0x07, 0x63]); // prefix
1296        macro_body.extend_from_slice(&obfuscated_stream);
1297
1298        let macro_rec_size = 6usize
1299            .saturating_add(name.len())
1300            .saturating_add(macro_body.len());
1301        let rec_size_u32 = u32::try_from(macro_rec_size)?;
1302
1303        let mut payload = Vec::new();
1304        payload.extend_from_slice(&rec_size_u32.to_le_bytes());
1305        payload.push(0x84);
1306        payload.push(u8::try_from(name.len())?);
1307        payload.extend_from_slice(name);
1308        payload.extend_from_slice(&macro_body);
1309
1310        let section_size = payload.len().saturating_add(12);
1311        let sec_size_u32 = u32::try_from(section_size)?;
1312
1313        pan_bytes.extend_from_slice(&sec_size_u32.to_le_bytes());
1314        pan_bytes.push(0x83);
1315        pan_bytes.push(6);
1316        pan_bytes.extend_from_slice(b"MACROS");
1317        pan_bytes.extend_from_slice(&payload);
1318
1319        let code = pan_to_macro(&pan_bytes, ".LockedProc")?;
1320        ensure!(code == "message \"Hello Locked\"\n");
1321
1322        Ok(())
1323    }
1324
1325    #[crate::ctb_test]
1326    fn test_pan_to_csv_run_startup_procedure() -> anyhow::Result<()> {
1327        let sample_bytes = crate::get_pan_data("fixtures/SAMPLE.pan")
1328            .context("Could not load fixtures/SAMPLE.pan")?;
1329        let options = PanCsvOptions {
1330            include_header: true,
1331            run_startup_procedure: true,
1332            ..Default::default()
1333        };
1334        let csv_output = pan_to_csv_with_options(&sample_bytes, &options)?;
1335        ensure!(!csv_output.is_empty());
1336        Ok(())
1337    }
1338
1339    fn build_sample_pan_with_macros(
1340        macros: &[(&str, &[u8])],
1341    ) -> anyhow::Result<Vec<u8>> {
1342        let mut pan_bytes = Vec::new();
1343        pan_bytes.extend_from_slice(&0u32.to_le_bytes());
1344        // Prelude entry
1345        pan_bytes.push(0x00);
1346        pan_bytes.push(4);
1347        pan_bytes.extend_from_slice(b"TEST");
1348        pan_bytes.push(0);
1349        pan_bytes.extend_from_slice(&0u32.to_le_bytes());
1350
1351        // Build MACROS section payload
1352        let mut payload = Vec::new();
1353        for &(name, code) in macros {
1354            let name_bytes = name.as_bytes();
1355            let name_len = u8::try_from(name_bytes.len())
1356                .context("Macro name too long")?;
1357            let code_len =
1358                u16::try_from(code.len()).context("Macro code too long")?;
1359            let macro_rec_size = usize::from(name_len)
1360                .saturating_add(usize::from(code_len))
1361                .saturating_add(8);
1362            let rec_size_u32 = u32::try_from(macro_rec_size)
1363                .context("Record size overflow")?;
1364            payload.extend_from_slice(&rec_size_u32.to_le_bytes());
1365            payload.push(0x84);
1366            payload.push(name_len);
1367            payload.extend_from_slice(name_bytes);
1368            payload.extend_from_slice(&code_len.to_le_bytes());
1369            payload.extend_from_slice(code);
1370        }
1371
1372        let section_size = payload.len().saturating_add(12);
1373        let sec_size_u32 =
1374            u32::try_from(section_size).context("Section size overflow")?;
1375        pan_bytes.extend_from_slice(&sec_size_u32.to_le_bytes());
1376        pan_bytes.push(0x83);
1377        pan_bytes.push(6);
1378        pan_bytes.extend_from_slice(b"MACROS");
1379        pan_bytes.extend_from_slice(&payload);
1380
1381        Ok(pan_bytes)
1382    }
1383
1384    #[crate::ctb_test]
1385    fn test_export_pan_procedures_creates_files_and_sanitizes_names()
1386    -> anyhow::Result<()> {
1387        let pan_bytes = build_sample_pan_with_macros(&[
1388            (".Initialize", b"global x\rx=1"),
1389            ("Reports/2026\0", b"message \"Done\""),
1390        ])?;
1391
1392        let temp = tempfile::tempdir()?;
1393        let out_dir = temp.path().join("procedures");
1394
1395        let summary = export_pan_procedures(
1396            Path::new("dummy.pan"),
1397            &pan_bytes,
1398            Some(&out_dir),
1399            None,
1400            PanCsvEncoding::Utf8,
1401        )?;
1402
1403        ensure!(summary.contains("Exported 2 procedure(s)"));
1404        ensure!(out_dir.join(".Initialize").exists());
1405        ensure!(out_dir.join("Reports⌿2026").exists());
1406
1407        let code1 = fs::read_to_string(out_dir.join(".Initialize"))?;
1408        ensure!(code1 == "global x\nx=1\n");
1409
1410        let code2 = fs::read_to_string(out_dir.join("Reports⌿2026"))?;
1411        ensure!(code2 == "message \"Done\"\n");
1412
1413        Ok(())
1414    }
1415
1416    #[crate::ctb_test]
1417    fn test_export_pan_procedures_with_extension() -> anyhow::Result<()> {
1418        let pan_bytes = build_sample_pan_with_macros(&[
1419            (".Initialize", b"global x"),
1420            ("Reports/Q1", b"message \"Q1\""),
1421        ])?;
1422
1423        let temp = tempfile::tempdir()?;
1424        let out_dir = temp.path().join("procedures_ext");
1425
1426        export_pan_procedures(
1427            Path::new("dummy.pan"),
1428            &pan_bytes,
1429            Some(&out_dir),
1430            Some("estes"),
1431            PanCsvEncoding::Utf8,
1432        )?;
1433
1434        ensure!(out_dir.join(".Initialize.estes").exists());
1435        ensure!(out_dir.join("Reports⌿Q1.estes").exists());
1436
1437        Ok(())
1438    }
1439
1440    #[crate::ctb_test]
1441    fn test_export_pan_procedures_errors_when_target_dir_exists()
1442    -> anyhow::Result<()> {
1443        let pan_bytes =
1444            build_sample_pan_with_macros(&[(".Initialize", b"global x")])?;
1445
1446        let temp = tempfile::tempdir()?;
1447        let out_dir = temp.path().join("already_exists");
1448        fs::create_dir(&out_dir)?;
1449
1450        let result = export_pan_procedures(
1451            Path::new("dummy.pan"),
1452            &pan_bytes,
1453            Some(&out_dir),
1454            None,
1455            PanCsvEncoding::Utf8,
1456        );
1457
1458        ensure!(result.is_err());
1459        let err = result.unwrap_err().to_string();
1460        ensure!(err.contains("Target directory already exists"));
1461
1462        Ok(())
1463    }
1464
1465    #[crate::ctb_test]
1466    fn test_export_pan_procedures_disambiguates_duplicate_names()
1467    -> anyhow::Result<()> {
1468        let pan_bytes = build_sample_pan_with_macros(&[
1469            ("Calculate", b"x=1"),
1470            ("Calculate", b"x=2"),
1471            ("Calculate", b"x=3"),
1472        ])?;
1473
1474        let temp = tempfile::tempdir()?;
1475        let out_dir = temp.path().join("dup_procedures");
1476
1477        export_pan_procedures(
1478            Path::new("dummy.pan"),
1479            &pan_bytes,
1480            Some(&out_dir),
1481            None,
1482            PanCsvEncoding::Utf8,
1483        )?;
1484
1485        ensure!(out_dir.join("Calculate").exists());
1486        ensure!(out_dir.join("Calculate_2").exists());
1487        ensure!(out_dir.join("Calculate_3").exists());
1488
1489        let code1 = fs::read_to_string(out_dir.join("Calculate"))?;
1490        let code2 = fs::read_to_string(out_dir.join("Calculate_2"))?;
1491        let code3 = fs::read_to_string(out_dir.join("Calculate_3"))?;
1492
1493        ensure!(code1 == "x=1\n");
1494        ensure!(code2 == "x=2\n");
1495        ensure!(code3 == "x=3\n");
1496
1497        Ok(())
1498    }
1499}