altium-cli 0.1.7

CLI tool for inspecting and manipulating Altium Designer files
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
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Alexander Kiselev <alex@akiselev.com>
//
//! Edit command implementation.
//!
//! Provides programmatic editing operations for Altium schematic documents.
//! Supports adding, moving, and deleting components, wires, and other primitives.

use std::path::Path;

use serde::Serialize;

use crate::output::{self, TextFormat};
use altium_format::edit::types::Orientation;
use altium_format::edit::EditSession;
use altium_format::records::sch::{PortIoType, PowerObjectStyle, TextOrientations};
use altium_format::types::{Coord, CoordPoint, Unit};

/// Result of an edit operation.
#[derive(Serialize)]
pub struct EditResult {
    /// Whether the operation succeeded.
    pub success: bool,
    /// Path to the edited file.
    pub file: String,
    /// The edit operation that was performed.
    pub operation: String,
    /// Description of what was changed.
    pub description: String,
    /// Output path where the file was saved.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_path: Option<String>,
    /// Error message if the operation failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

impl TextFormat for EditResult {
    fn format_text(&self) -> String {
        let mut output = String::new();

        if self.success {
            output.push_str("✓ Success\n");
        } else {
            output.push_str("✗ Failed\n");
        }

        output.push_str(&format!("Operation: {}\n", self.operation));
        output.push_str(&format!("File: {}\n", self.file));
        output.push_str(&format!("{}\n", self.description));

        if let Some(out_path) = &self.output_path {
            output.push_str(&format!("Saved to: {}\n", out_path));
        }

        if let Some(err) = &self.error {
            output.push_str(&format!("Error: {}\n", err));
        }

        output
    }
}

/// Edit subcommand specification.
#[derive(Debug, Clone)]
pub enum EditOperation {
    /// Move a component to a new location.
    MoveComponent { designator: String, x: f64, y: f64 },
    /// Delete a component by designator.
    DeleteComponent { designator: String },
    /// Add a wire with given vertices (x1,y1,x2,y2,...).
    AddWire { vertices: Vec<f64> },
    /// Delete a wire by index.
    DeleteWire { index: usize },
    /// Add a net label at a location.
    AddNetLabel { name: String, x: f64, y: f64 },
    /// Add a power port.
    AddPower {
        name: String,
        x: f64,
        y: f64,
        style: String,
        orientation: String,
    },
    /// Add a junction.
    AddJunction { x: f64, y: f64 },
    /// Add missing junctions where wires cross.
    AddMissingJunctions,
    /// Add a port.
    AddPort {
        name: String,
        x: f64,
        y: f64,
        io_type: String,
    },
    /// Route a wire between two points.
    RouteWire { from: String, to: String },
    /// Validate the schematic.
    Validate,
    /// Add component from library.
    AddComponent {
        library: String,
        component: String,
        x: f64,
        y: f64,
        designator: Option<String>,
    },
}

/// Run the edit command.
pub fn run(
    path: &Path,
    operation: &str,
    format: &str,
    output_file: Option<&Path>,
) -> Result<(), Box<dyn std::error::Error>> {
    let op = parse_operation(operation)?;

    let result = execute_operation(path, op, output_file)?;

    output::print(&result, format)?;

    if !result.success {
        std::process::exit(1);
    }

    Ok(())
}

/// Parse an operation string into an EditOperation.
///
/// Supported formats:
/// - `move <designator> <x> <y>` - Move component to (x, y) mils
/// - `delete <designator>` - Delete component
/// - `add-wire <x1>,<y1>,<x2>,<y2>,...` - Add wire with vertices
/// - `delete-wire <index>` - Delete wire by index
/// - `add-net-label <name> <x> <y>` - Add net label
/// - `add-power <name> <x> <y> <style> <orientation>` - Add power port
/// - `add-junction <x> <y>` - Add junction
/// - `add-missing-junctions` - Add junctions where wires cross
/// - `add-port <name> <x> <y> <io_type>` - Add port
/// - `route <from> <to>` - Route wire between points
/// - `validate` - Validate the schematic
fn parse_operation(operation: &str) -> Result<EditOperation, Box<dyn std::error::Error>> {
    let parts: Vec<&str> = operation.split_whitespace().collect();
    if parts.is_empty() {
        return Err("Empty operation".into());
    }

    match parts[0].to_lowercase().as_str() {
        "move" => {
            if parts.len() < 4 {
                return Err("move requires: <designator> <x> <y>".into());
            }
            let x = parse_coordinate(parts[2])?;
            let y = parse_coordinate(parts[3])?;
            Ok(EditOperation::MoveComponent {
                designator: parts[1].to_string(),
                x,
                y,
            })
        }
        "delete" => {
            if parts.len() < 2 {
                return Err("delete requires: <designator>".into());
            }
            Ok(EditOperation::DeleteComponent {
                designator: parts[1].to_string(),
            })
        }
        "add-wire" => {
            if parts.len() < 2 {
                return Err("add-wire requires: <x1>,<y1>,<x2>,<y2>,...".into());
            }
            let vertices = parse_vertex_list(parts[1])?;
            if vertices.len() < 4 || vertices.len() % 2 != 0 {
                return Err("add-wire requires at least 2 coordinate pairs (4 values)".into());
            }
            Ok(EditOperation::AddWire { vertices })
        }
        "delete-wire" => {
            if parts.len() < 2 {
                return Err("delete-wire requires: <index>".into());
            }
            let index: usize = parts[1]
                .parse()
                .map_err(|_| format!("Invalid wire index: {}", parts[1]))?;
            Ok(EditOperation::DeleteWire { index })
        }
        "add-net-label" => {
            if parts.len() < 4 {
                return Err("add-net-label requires: <name> <x> <y>".into());
            }
            let x = parse_coordinate(parts[2])?;
            let y = parse_coordinate(parts[3])?;
            Ok(EditOperation::AddNetLabel {
                name: parts[1].to_string(),
                x,
                y,
            })
        }
        "add-power" => {
            if parts.len() < 6 {
                return Err("add-power requires: <name> <x> <y> <style> <orientation>".into());
            }
            let x = parse_coordinate(parts[2])?;
            let y = parse_coordinate(parts[3])?;
            Ok(EditOperation::AddPower {
                name: parts[1].to_string(),
                x,
                y,
                style: parts[4].to_string(),
                orientation: parts[5].to_string(),
            })
        }
        "add-junction" => {
            if parts.len() < 3 {
                return Err("add-junction requires: <x> <y>".into());
            }
            let x = parse_coordinate(parts[1])?;
            let y = parse_coordinate(parts[2])?;
            Ok(EditOperation::AddJunction { x, y })
        }
        "add-missing-junctions" => Ok(EditOperation::AddMissingJunctions),
        "add-port" => {
            if parts.len() < 5 {
                return Err("add-port requires: <name> <x> <y> <io_type>".into());
            }
            let x = parse_coordinate(parts[2])?;
            let y = parse_coordinate(parts[3])?;
            Ok(EditOperation::AddPort {
                name: parts[1].to_string(),
                x,
                y,
                io_type: parts[4].to_string(),
            })
        }
        "route" => {
            if parts.len() < 3 {
                return Err("route requires: <from> <to>".into());
            }
            Ok(EditOperation::RouteWire {
                from: parts[1].to_string(),
                to: parts[2].to_string(),
            })
        }
        "validate" => Ok(EditOperation::Validate),
        "add-component" => {
            if parts.len() < 5 {
                return Err(
                    "add-component requires: <library> <component> <x> <y> [designator]".into(),
                );
            }
            let x = parse_coordinate(parts[3])?;
            let y = parse_coordinate(parts[4])?;
            let designator = if parts.len() >= 6 {
                Some(parts[5].to_string())
            } else {
                None
            };
            Ok(EditOperation::AddComponent {
                library: parts[1].to_string(),
                component: parts[2].to_string(),
                x,
                y,
                designator,
            })
        }
        _ => Err(format!("Unknown operation: {}", parts[0]).into()),
    }
}

/// Parse a coordinate value with optional unit suffix.
fn parse_coordinate(s: &str) -> Result<f64, Box<dyn std::error::Error>> {
    let s = s.trim();

    if let Ok((coord, unit)) = Unit::parse_with_unit(s) {
        if unit != Unit::DxpDefault {
            return Ok(coord.to_mils());
        }
    }

    s.parse::<f64>()
        .map_err(|_| {
            format!(
                "Invalid coordinate '{}': expected number with optional unit (e.g., '100mil', '2.54mm')",
                s
            )
            .into()
        })
}

/// Parse a comma-separated list of vertex coordinates.
fn parse_vertex_list(s: &str) -> Result<Vec<f64>, Box<dyn std::error::Error>> {
    s.split(',')
        .map(|v| {
            v.trim()
                .parse::<f64>()
                .map_err(|_| format!("Invalid vertex coordinate: {}", v))
        })
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| e.into())
}

/// Execute an edit operation on the file.
fn execute_operation(
    path: &Path,
    operation: EditOperation,
    output_file: Option<&Path>,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let output_path = output_file.unwrap_or(path);

    match operation {
        EditOperation::MoveComponent { designator, x, y } => {
            execute_move_component(path, &designator, x, y, output_path)
        }
        EditOperation::DeleteComponent { designator } => {
            execute_delete_component(path, &designator, output_path)
        }
        EditOperation::AddWire { vertices } => execute_add_wire(path, &vertices, output_path),
        EditOperation::DeleteWire { index } => execute_delete_wire(path, index, output_path),
        EditOperation::AddNetLabel { name, x, y } => {
            execute_add_net_label(path, &name, x, y, output_path)
        }
        EditOperation::AddPower {
            name,
            x,
            y,
            style,
            orientation,
        } => execute_add_power(path, &name, x, y, &style, &orientation, output_path),
        EditOperation::AddJunction { x, y } => execute_add_junction(path, x, y, output_path),
        EditOperation::AddMissingJunctions => execute_add_missing_junctions(path, output_path),
        EditOperation::AddPort {
            name,
            x,
            y,
            io_type,
        } => execute_add_port(path, &name, x, y, &io_type, output_path),
        EditOperation::RouteWire { from, to } => execute_route_wire(path, &from, &to, output_path),
        EditOperation::Validate => execute_validate(path),
        EditOperation::AddComponent {
            library,
            component,
            x,
            y,
            designator,
        } => execute_add_component(
            path,
            &library,
            &component,
            x,
            y,
            designator.as_deref(),
            output_path,
        ),
    }
}

fn execute_move_component(
    path: &Path,
    designator: &str,
    x: f64,
    y: f64,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;

    let components = session
        .layout()
        .get_placed_components(&session.doc.primitives);
    let comp = components
        .iter()
        .find(|c| c.designator == designator)
        .ok_or_else(|| format!("Component not found: {}", designator))?;

    let index = comp.index;
    let new_location = CoordPoint::from_mils(x, y);

    session.move_component(index, new_location)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "move".to_string(),
        description: format!("Moved {} to ({:.0}, {:.0}) mils", designator, x, y),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_delete_component(
    path: &Path,
    designator: &str,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;

    let components = session
        .layout()
        .get_placed_components(&session.doc.primitives);
    let comp = components
        .iter()
        .find(|c| c.designator == designator)
        .ok_or_else(|| format!("Component not found: {}", designator))?;

    let index = comp.index;
    session.delete_component(index)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "delete".to_string(),
        description: format!("Deleted component {}", designator),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_add_wire(
    path: &Path,
    vertices: &[f64],
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;

    let points: Vec<CoordPoint> = vertices
        .chunks(2)
        .map(|chunk| CoordPoint::from_mils(chunk[0], chunk[1]))
        .collect();

    session.add_wire(&points)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "add-wire".to_string(),
        description: format!("Added wire with {} vertices", points.len()),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_delete_wire(
    path: &Path,
    index: usize,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;
    session.delete_wire(index)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "delete-wire".to_string(),
        description: format!("Deleted wire at index {}", index),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_add_net_label(
    path: &Path,
    name: &str,
    x: f64,
    y: f64,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;
    let location = CoordPoint::from_mils(x, y);
    session.add_net_label(name, location)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "add-net-label".to_string(),
        description: format!("Added net label '{}' at ({:.0}, {:.0}) mils", name, x, y),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_add_power(
    path: &Path,
    name: &str,
    x: f64,
    y: f64,
    style: &str,
    orientation: &str,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;
    let location = CoordPoint::from_mils(x, y);

    let power_style = match style.to_lowercase().as_str() {
        "bar" | "power_bar" => PowerObjectStyle::Bar,
        "arrow" => PowerObjectStyle::Arrow,
        "wave" => PowerObjectStyle::Wave,
        "ground" | "gnd" => PowerObjectStyle::Ground,
        "power_ground" | "pgnd" => PowerObjectStyle::PowerGround,
        "signal_ground" | "sgnd" => PowerObjectStyle::SignalGround,
        "earth_ground" | "earth" => PowerObjectStyle::EarthGround,
        "circle" => PowerObjectStyle::Circle,
        _ => {
            return Err(format!(
                "Unknown power style: {}. Use: bar, arrow, wave, ground, power_ground, signal_ground, earth_ground, circle",
                style
            )
            .into())
        }
    };

    let orient = match orientation.to_lowercase().as_str() {
        "up" | "0" => TextOrientations::NONE,
        "left" | "90" => TextOrientations::ROTATED,
        "down" | "180" => TextOrientations::FLIPPED,
        "right" | "270" => TextOrientations::ROTATED | TextOrientations::FLIPPED,
        _ => {
            return Err(format!(
                "Unknown orientation: {}. Use: up, down, left, right",
                orientation
            )
            .into());
        }
    };

    session.add_power_port(name, location, power_style, orient)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "add-power".to_string(),
        description: format!(
            "Added power port '{}' ({}) at ({:.0}, {:.0}) mils",
            name, style, x, y
        ),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_add_junction(
    path: &Path,
    x: f64,
    y: f64,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;
    let location = CoordPoint::from_mils(x, y);
    session.add_junction(location)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "add-junction".to_string(),
        description: format!("Added junction at ({:.0}, {:.0}) mils", x, y),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_add_missing_junctions(
    path: &Path,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;
    let count = session.add_missing_junctions()?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "add-missing-junctions".to_string(),
        description: format!("Added {} missing junction(s)", count),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_add_port(
    path: &Path,
    name: &str,
    x: f64,
    y: f64,
    io_type: &str,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;
    let location = CoordPoint::from_mils(x, y);

    let port_io_type = match io_type.to_lowercase().as_str() {
        "input" | "in" => PortIoType::Input,
        "output" | "out" => PortIoType::Output,
        "bidirectional" | "bidir" | "inout" => PortIoType::Bidirectional,
        "unspecified" | "none" => PortIoType::Unspecified,
        _ => {
            return Err(format!(
                "Unknown I/O type: {}. Use: input, output, bidirectional, unspecified",
                io_type
            )
            .into());
        }
    };

    session.add_port(name, location, port_io_type)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "add-port".to_string(),
        description: format!(
            "Added port '{}' ({}) at ({:.0}, {:.0}) mils",
            name, io_type, x, y
        ),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_route_wire(
    path: &Path,
    from: &str,
    to: &str,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;

    let start = parse_point_spec(from, &session)?;
    let end = parse_point_spec(to, &session)?;

    session.route_wire(start, end)?;
    session.save(output_path)?;

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "route".to_string(),
        description: format!("Routed wire from {} to {}", from, to),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

fn execute_validate(path: &Path) -> Result<EditResult, Box<dyn std::error::Error>> {
    let session = EditSession::open(path)?;
    let errors = session.validate();

    if errors.is_empty() {
        Ok(EditResult {
            success: true,
            file: path.display().to_string(),
            operation: "validate".to_string(),
            description: "Schematic is valid".to_string(),
            output_path: None,
            error: None,
        })
    } else {
        let error_descriptions: Vec<String> = errors
            .iter()
            .map(|e| format!("{:?}: {}", e.kind, e.message))
            .collect();

        Ok(EditResult {
            success: false,
            file: path.display().to_string(),
            operation: "validate".to_string(),
            description: format!("Found {} validation error(s)", errors.len()),
            output_path: None,
            error: Some(error_descriptions.join("; ")),
        })
    }
}

fn execute_add_component(
    path: &Path,
    library: &str,
    component: &str,
    x: f64,
    y: f64,
    designator: Option<&str>,
    output_path: &Path,
) -> Result<EditResult, Box<dyn std::error::Error>> {
    let mut session = EditSession::open(path)?;
    let location = CoordPoint::from_mils(x, y);

    // Load the library
    session.load_library(library)?;

    // Add the component
    session.add_component(component, location, Orientation::Normal, designator)?;
    session.save(output_path)?;

    let des_desc = designator
        .map(|d| format!(" as {}", d))
        .unwrap_or_default();

    Ok(EditResult {
        success: true,
        file: path.display().to_string(),
        operation: "add-component".to_string(),
        description: format!(
            "Added component '{}' from '{}'{}at ({:.0}, {:.0}) mils",
            component, library, des_desc, x, y
        ),
        output_path: Some(output_path.display().to_string()),
        error: None,
    })
}

/// Parse a point specification for routing targets.
///
/// Supported formats:
/// - `x,y` - Coordinate pair in mils
/// - `Component.Pin` - Pin location (e.g., `U1.VCC`)
/// - `:PortName` - Port location
/// - `%NetLabel` - Net label location
/// - `@PowerPort` - Power port location
fn parse_point_spec(
    spec: &str,
    session: &EditSession,
) -> Result<CoordPoint, Box<dyn std::error::Error>> {
    use altium_format::records::sch::SchRecord;

    if let Some((x_str, y_str)) = spec.split_once(',') {
        let x: f64 = x_str.trim().parse().map_err(|_| {
            format!(
                "Invalid x coordinate in '{}'. Use: Component.Pin, :Port, %NetLabel, @Power, or x,y",
                spec
            )
        })?;
        let y: f64 = y_str.trim().parse().map_err(|_| {
            format!(
                "Invalid y coordinate in '{}'. Use: Component.Pin, :Port, %NetLabel, @Power, or x,y",
                spec
            )
        })?;
        return Ok(CoordPoint::from_mils(x, y));
    }

    if let Some(port_name) = spec.strip_prefix(':') {
        for record in &session.doc.primitives {
            if let SchRecord::Port(port) = record {
                if port.name == port_name {
                    return Ok(CoordPoint::new(
                        Coord::from_raw(port.graphical.location_x),
                        Coord::from_raw(port.graphical.location_y),
                    ));
                }
            }
        }
        return Err(format!("Port not found: '{}'", port_name).into());
    }

    if let Some(label_name) = spec.strip_prefix('%') {
        for record in &session.doc.primitives {
            if let SchRecord::NetLabel(label) = record {
                if label.label.text == label_name {
                    return Ok(CoordPoint::new(
                        Coord::from_raw(label.label.graphical.location_x),
                        Coord::from_raw(label.label.graphical.location_y),
                    ));
                }
            }
        }
        return Err(format!("Net label not found: '{}'", label_name).into());
    }

    if let Some(power_name) = spec.strip_prefix('@') {
        for record in &session.doc.primitives {
            if let SchRecord::PowerObject(power) = record {
                if power.text == power_name {
                    return Ok(CoordPoint::new(
                        Coord::from_raw(power.graphical.location_x),
                        Coord::from_raw(power.graphical.location_y),
                    ));
                }
            }
        }
        return Err(format!("Power port not found: '{}'", power_name).into());
    }

    if let Some((component, pin)) = spec.split_once('.') {
        let components = session
            .layout()
            .get_placed_components(&session.doc.primitives);
        let comp = components
            .iter()
            .find(|c| c.designator == component)
            .ok_or_else(|| {
                format!(
                    "Component not found: '{}'. Available: {:?}",
                    component,
                    components.iter().map(|c| &c.designator).collect::<Vec<_>>()
                )
            })?;

        let pin_loc = comp
            .pin_locations
            .iter()
            .find(|p| p.designator == pin || p.name == pin)
            .ok_or_else(|| {
                format!(
                    "Pin '{}' not found on component '{}'. Available: {:?}",
                    pin,
                    component,
                    comp.pin_locations
                        .iter()
                        .map(|p| format!("{}/{}", p.designator, p.name))
                        .collect::<Vec<_>>()
                )
            })?;

        return Ok(pin_loc.location);
    }

    Err(format!(
        "Invalid point specification: '{}'. Expected: Component.Pin, :Port, %NetLabel, @Power, or x,y",
        spec
    )
    .into())
}