tldr-core 0.1.6

Core analysis engine for TLDR code analysis tool
Documentation
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
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
//! Test module for architecture analysis commands: arch gaps, patterns, inheritance
//!
//! These tests define expected behavior BEFORE implementation.
//! Tests are designed to FAIL until the modules are implemented.
//!
//! # Test Categories
//!
//! ## 1. arch gaps tests (--generate-rules, --check-rules, Tarjan SCC)
//! - Rule generation in YAML/JSON format
//! - Layer constraints (LOW may not import HIGH)
//! - Cycle break recommendations
//! - Rule checking and violation detection
//! - Tarjan SCC algorithm for precise cycle detection
//!
//! ## 2. patterns tests
//! - Soft delete detection (is_deleted, deleted_at fields)
//! - Error handling patterns (try/catch, Result types)
//! - Naming conventions (snake_case, PascalCase)
//! - Resource management (context managers, defer, RAII)
//! - Multi-language support
//!
//! ## 3. inheritance tests
//! - Class hierarchy extraction (Python, TypeScript)
//! - ABC/Protocol/Interface detection
//! - Mixin class detection
//! - Diamond inheritance detection
//! - Output formats (JSON, DOT, text)
//! - Class filter with fuzzy matching
//!
//! Reference: architecture-spec.md


// =============================================================================
// Test Fixture Setup Module
// =============================================================================

/// Test fixture utilities for architecture analysis tests
pub mod fixtures {
    use std::path::{Path, PathBuf};
    use tempfile::TempDir;

    /// A temporary directory for testing architecture analysis
    pub struct TestDir {
        pub dir: TempDir,
    }

    impl TestDir {
        /// Create a new empty temporary directory
        pub fn new() -> std::io::Result<Self> {
            let dir = TempDir::new()?;
            Ok(Self { dir })
        }

        /// Get the path to the directory
        pub fn path(&self) -> &Path {
            self.dir.path()
        }

        /// Add a file to the directory
        pub fn add_file(&self, name: &str, content: &str) -> std::io::Result<PathBuf> {
            let path = self.dir.path().join(name);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&path, content)?;
            Ok(path)
        }

    }

    // -------------------------------------------------------------------------
    // arch Rules Fixtures
    // -------------------------------------------------------------------------

    /// Layered project for rules generation testing
    pub const LAYERED_PROJECT_API: &str = r#"
from services.user_service import UserService

def get_user(user_id: int):
    service = UserService()
    return service.find_by_id(user_id)

def create_user(name: str):
    service = UserService()
    return service.create(name)
"#;

    pub const LAYERED_PROJECT_SERVICE: &str = r#"
from utils.db import query, insert

class UserService:
    def find_by_id(self, user_id: int):
        return query("SELECT * FROM users WHERE id = ?", user_id)

    def create(self, name: str):
        return insert("users", {"name": name})
"#;

    pub const LAYERED_PROJECT_UTILS: &str = r#"
def query(sql: str, *args):
    return []

def insert(table: str, data: dict):
    return {"id": 1}
"#;

    /// Violating project - utils imports api (LOW imports HIGH)
    pub const VIOLATING_UTILS: &str = r#"
# BAD: Utility layer importing from API layer
from api.routes import get_user

def format_user(user_id: int):
    user = get_user(user_id)  # Violation: LOW -> HIGH
    return str(user)
"#;

    /// Circular dependency between services and api
    pub const CIRCULAR_API: &str = r#"
from services.auth import validate_token

def protected_route():
    return validate_token()
"#;

    pub const CIRCULAR_SERVICE: &str = r#"
from api.routes import protected_route  # Creates cycle

def validate_token():
    # This creates a circular dependency
    return True
"#;

    // -------------------------------------------------------------------------
    // Tarjan SCC Fixtures
    // -------------------------------------------------------------------------

    /// Simple 2-node cycle: A <-> B
    pub const SIMPLE_CYCLE: &str = r#"
def func_a():
    return func_b()

def func_b():
    return func_a()  # A -> B -> A
"#;

    /// Complex 3-node cycle: A -> B -> C -> A
    pub const COMPLEX_CYCLE: &str = r#"
def node_a():
    return node_b()

def node_b():
    return node_c()

def node_c():
    return node_a()  # A -> B -> C -> A
"#;

    /// Multiple SCCs in one graph
    pub const MULTIPLE_SCCS: &str = r#"
# SCC 1: cycle_a <-> cycle_b
def cycle_a():
    return cycle_b()

def cycle_b():
    return cycle_a()

# SCC 2: loop_x -> loop_y -> loop_z -> loop_x
def loop_x():
    return loop_y()

def loop_y():
    return loop_z()

def loop_z():
    return loop_x()

# Non-cycle: isolated functions
def standalone():
    return 42
"#;

    /// DAG (no cycles) - should find no SCCs > 1 node
    pub const DAG_NO_CYCLES: &str = r#"
def root():
    branch_a()
    branch_b()

def branch_a():
    leaf()

def branch_b():
    leaf()

def leaf():
    return 42
"#;

    // -------------------------------------------------------------------------
    // patterns Fixtures
    // -------------------------------------------------------------------------

    /// Python soft delete pattern
    pub const PYTHON_SOFT_DELETE: &str = r#"
from sqlalchemy import Column, Boolean, DateTime

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    is_deleted = Column(Boolean, default=False)
    deleted_at = Column(DateTime, nullable=True)

    def soft_delete(self):
        self.is_deleted = True
        self.deleted_at = datetime.now()
"#;

    /// TypeScript soft delete pattern
    pub const TYPESCRIPT_SOFT_DELETE: &str = r#"
interface User {
    id: number;
    name: string;
    isDeleted: boolean;
    deletedAt: Date | null;
}

class UserModel {
    softDelete(user: User): void {
        user.isDeleted = true;
        user.deletedAt = new Date();
    }
}
"#;

    /// Python error handling patterns
    pub const PYTHON_ERROR_HANDLING: &str = r#"
class ValidationError(Exception):
    """Custom validation error"""
    pass

class NotFoundError(Exception):
    """Resource not found"""
    pass

def process_data(data):
    try:
        validate(data)
        return transform(data)
    except ValidationError as e:
        logger.error(f"Validation failed: {e}")
        raise
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        raise NotFoundError("Data processing failed")
"#;

    /// Rust error handling with Result
    pub const RUST_ERROR_HANDLING: &str = r#"
use std::io;

#[derive(Debug)]
pub enum AppError {
    IoError(io::Error),
    ValidationError(String),
}

pub fn process_file(path: &str) -> Result<String, AppError> {
    let content = std::fs::read_to_string(path)
        .map_err(AppError::IoError)?;

    if content.is_empty() {
        return Err(AppError::ValidationError("Empty file".into()));
    }

    Ok(content)
}
"#;

    /// Go error handling pattern
    pub const GO_ERROR_HANDLING: &str = r#"
package main

import (
    "errors"
    "fmt"
)

var ErrNotFound = errors.New("not found")

func FindUser(id int) (*User, error) {
    user, err := db.Query(id)
    if err != nil {
        return nil, fmt.Errorf("query failed: %w", err)
    }
    if user == nil {
        return nil, ErrNotFound
    }
    return user, nil
}
"#;

    /// Python naming conventions (snake_case)
    pub const PYTHON_NAMING: &str = r#"
GLOBAL_CONSTANT = 42
MAX_RETRY_COUNT = 3

class UserService:
    def __init__(self):
        self._private_field = None

    def find_user_by_id(self, user_id: int):
        return self._query_database(user_id)

    def _query_database(self, user_id: int):
        return None

def helper_function():
    local_variable = 10
    return local_variable
"#;

    /// TypeScript naming conventions (camelCase/PascalCase)
    pub const TYPESCRIPT_NAMING: &str = r#"
const GLOBAL_CONSTANT = 42;
const maxRetryCount = 3;

class UserService {
    private privateField: string;

    findUserById(userId: number): User | null {
        return this.queryDatabase(userId);
    }

    private queryDatabase(userId: number): User | null {
        return null;
    }
}

function helperFunction(): number {
    const localVariable = 10;
    return localVariable;
}
"#;

    /// Python context manager pattern
    pub const PYTHON_CONTEXT_MANAGER: &str = r#"
class FileManager:
    def __init__(self, filename):
        self.filename = filename
        self.file = None

    def __enter__(self):
        self.file = open(self.filename, 'r')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

def process_file(filename):
    with FileManager(filename) as f:
        return f.read()

    # Also with standard library
    with open("other.txt") as f:
        content = f.read()
"#;

    /// Go defer pattern
    pub const GO_DEFER: &str = r#"
package main

import "os"

func processFile(filename string) error {
    f, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer f.Close()

    // Process file...
    return nil
}
"#;

    /// Rust RAII pattern
    pub const RUST_RAII: &str = r#"
use std::fs::File;
use std::io::Read;

struct FileHandle {
    file: File,
}

impl Drop for FileHandle {
    fn drop(&mut self) {
        // File automatically closed when dropped
        println!("Closing file");
    }
}

fn process_file(path: &str) -> std::io::Result<String> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
    // File automatically closed here
}
"#;

    // -------------------------------------------------------------------------
    // inheritance Fixtures
    // -------------------------------------------------------------------------

    /// Python class hierarchy
    pub const PYTHON_INHERITANCE: &str = r#"
from abc import ABC, abstractmethod
from typing import Protocol

class Animal(ABC):
    @abstractmethod
    def speak(self) -> str:
        pass

class Mammal(Animal):
    def breathe(self):
        return "breathing"

class Dog(Mammal):
    def speak(self) -> str:
        return "woof"

class Cat(Mammal):
    def speak(self) -> str:
        return "meow"

# Protocol example
class Serializable(Protocol):
    def serialize(self) -> dict:
        ...

# External base class (from library)
class MyException(Exception):
    pass
"#;

    /// Python mixin pattern
    pub const PYTHON_MIXIN: &str = r#"
class TimestampMixin:
    created_at = None
    updated_at = None

    def touch(self):
        self.updated_at = datetime.now()

class AuditMixin:
    created_by = None
    updated_by = None

class User(Base, TimestampMixin, AuditMixin):
    __tablename__ = 'users'
    name = Column(String)

class Post(Base, TimestampMixin):
    __tablename__ = 'posts'
    title = Column(String)
"#;

    /// Python diamond inheritance
    pub const PYTHON_DIAMOND: &str = r#"
class Base:
    def method(self):
        return "base"

class ParentA(Base):
    def method_a(self):
        return "A"

class ParentB(Base):
    def method_b(self):
        return "B"

class Diamond(ParentA, ParentB):
    # Diamond inheritance: Diamond -> ParentA -> Base
    #                      Diamond -> ParentB -> Base
    def method(self):
        return super().method()  # Uses MRO
"#;

    /// TypeScript class hierarchy
    pub const TYPESCRIPT_INHERITANCE: &str = r#"
interface Serializable {
    serialize(): string;
}

abstract class Animal {
    abstract speak(): string;
}

class Mammal extends Animal {
    breathe(): string {
        return "breathing";
    }

    speak(): string {
        return "generic mammal sound";
    }
}

class Dog extends Mammal implements Serializable {
    speak(): string {
        return "woof";
    }

    serialize(): string {
        return JSON.stringify({ type: "Dog" });
    }
}

// Multiple interfaces
interface Walkable {
    walk(): void;
}

class Cat extends Mammal implements Serializable, Walkable {
    speak(): string {
        return "meow";
    }

    serialize(): string {
        return JSON.stringify({ type: "Cat" });
    }

    walk(): void {
        console.log("walking");
    }
}
"#;

}

// =============================================================================
// arch Rules Tests (--generate-rules, --check-rules)
// =============================================================================

#[cfg(test)]
mod arch_rules_tests {
    use super::fixtures::*;

    // -------------------------------------------------------------------------
    // Rule Generation Tests
    // -------------------------------------------------------------------------

    /// Test that --generate-rules produces valid YAML format
    /// Contract: Output must be parseable YAML with version, layers, rules keys
    #[test]
    #[ignore = "arch --generate-rules not yet implemented"]
    fn generate_rules_yaml_format() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("api/routes.py", LAYERED_PROJECT_API)
            .unwrap();
        test_dir
            .add_file("services/user_service.py", LAYERED_PROJECT_SERVICE)
            .unwrap();
        test_dir
            .add_file("utils/db.py", LAYERED_PROJECT_UTILS)
            .unwrap();

        // Expected: generate_rules returns YAML string with required keys
        // let rules_yaml = generate_architecture_rules(test_dir.path(), OutputFormat::Yaml).unwrap();
        //
        // Parse YAML and verify structure:
        // - version: "1.0"
        // - generated_at: ISO8601 timestamp
        // - layers: { high: {...}, middle: {...}, low: {...} }
        // - rules: [ { id, constraint, type, ... }, ... ]

        todo!("Implement generate_rules_yaml_format test");
    }

    /// Test that generated rules include layer constraints
    /// Contract: L1 (LOW -> HIGH forbidden), L2 (MIDDLE -> HIGH forbidden)
    #[test]
    #[ignore = "arch --generate-rules not yet implemented"]
    fn generate_rules_includes_layer_constraints() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("api/routes.py", LAYERED_PROJECT_API)
            .unwrap();
        test_dir
            .add_file("services/user_service.py", LAYERED_PROJECT_SERVICE)
            .unwrap();
        test_dir
            .add_file("utils/db.py", LAYERED_PROJECT_UTILS)
            .unwrap();

        // Expected: rules contain L1 and L2 constraints
        // let rules = generate_architecture_rules(test_dir.path(), OutputFormat::Json).unwrap();
        // let parsed: ArchRules = serde_json::from_str(&rules).unwrap();
        //
        // assert!(parsed.rules.iter().any(|r| r.id == "L1"));
        // assert!(parsed.rules.iter().any(|r| r.id == "L2"));
        //
        // let l1 = parsed.rules.iter().find(|r| r.id == "L1").unwrap();
        // assert_eq!(l1.from_layers, vec!["LOW"]);
        // assert_eq!(l1.to_layers, vec!["HIGH"]);
        // assert_eq!(l1.rule_type, RuleType::Layer);

        todo!("Implement generate_rules_includes_layer_constraints test");
    }

    /// Test that generated rules include cycle break recommendations
    /// Contract: C1, C2, ... rules for detected circular dependencies
    #[test]
    #[ignore = "arch --generate-rules not yet implemented"]
    fn generate_rules_includes_cycle_breaks() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("api/routes.py", CIRCULAR_API).unwrap();
        test_dir
            .add_file("services/auth.py", CIRCULAR_SERVICE)
            .unwrap();

        // Expected: rules contain C1 cycle-break recommendation
        // let rules = generate_architecture_rules(test_dir.path(), OutputFormat::Json).unwrap();
        // let parsed: ArchRules = serde_json::from_str(&rules).unwrap();
        //
        // let cycle_rules: Vec<_> = parsed.rules.iter()
        //     .filter(|r| r.rule_type == RuleType::CycleBreak)
        //     .collect();
        //
        // assert!(!cycle_rules.is_empty(), "Expected at least one cycle-break rule");
        // assert!(cycle_rules[0].id.starts_with("C"));
        // assert!(cycle_rules[0].files.len() >= 2);

        todo!("Implement generate_rules_includes_cycle_breaks test");
    }

    // -------------------------------------------------------------------------
    // Rule Checking Tests
    // -------------------------------------------------------------------------

    /// Test that --check-rules detects layer violations
    /// Contract: Violation when LOW imports HIGH
    #[test]
    #[ignore = "arch --check-rules not yet implemented"]
    fn check_rules_detects_layer_violation() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("api/routes.py", LAYERED_PROJECT_API)
            .unwrap();
        test_dir
            .add_file("services/user_service.py", LAYERED_PROJECT_SERVICE)
            .unwrap();
        test_dir.add_file("utils/db.py", VIOLATING_UTILS).unwrap();

        // Create rules file
        let rules = r#"
version: "1.0"
layers:
  high: { directories: ["api/"] }
  middle: { directories: ["services/"] }
  low: { directories: ["utils/"] }
rules:
  - id: L1
    constraint: "LOW may not import HIGH"
    type: layer
    from_layers: [LOW]
    to_layers: [HIGH]
    severity: error
"#;
        test_dir.add_file("arch-rules.yaml", rules).unwrap();

        // Expected: check_rules returns violations
        // let report = check_architecture_rules(test_dir.path(), "arch-rules.yaml").unwrap();
        //
        // assert!(!report.pass);
        // assert!(!report.violations.is_empty());
        //
        // let violation = &report.violations[0];
        // assert_eq!(violation.rule_id, "L1");
        // assert!(violation.from_file.contains("utils"));
        // assert!(violation.imports_file.contains("api"));
        // assert_eq!(violation.severity, Severity::Error);

        todo!("Implement check_rules_detects_layer_violation test");
    }

    /// Test that --check-rules detects cycle violations
    /// Contract: Violation when cycle-break rule files both import each other
    #[test]
    #[ignore = "arch --check-rules not yet implemented"]
    fn check_rules_detects_cycle_violation() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("api/routes.py", CIRCULAR_API).unwrap();
        test_dir
            .add_file("services/auth.py", CIRCULAR_SERVICE)
            .unwrap();

        // Create rules file with cycle-break rule
        let rules = r#"
version: "1.0"
rules:
  - id: C1
    constraint: "Break cycle: services/auth.py should not import api/routes.py"
    type: cycle_break
    files:
      - "services/auth.py"
      - "api/routes.py"
    severity: warn
"#;
        test_dir.add_file("arch-rules.yaml", rules).unwrap();

        // Expected: check_rules returns cycle violation
        // let report = check_architecture_rules(test_dir.path(), "arch-rules.yaml").unwrap();
        //
        // let cycle_violations: Vec<_> = report.violations.iter()
        //     .filter(|v| v.rule_id.starts_with("C"))
        //     .collect();
        //
        // assert!(!cycle_violations.is_empty());
        // assert_eq!(cycle_violations[0].severity, Severity::Warn);

        todo!("Implement check_rules_detects_cycle_violation test");
    }

    /// Test that --check-rules allows valid dependencies
    /// Contract: No violations when dependencies follow layer rules
    #[test]
    #[ignore = "arch --check-rules not yet implemented"]
    fn check_rules_allows_valid_dependencies() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("api/routes.py", LAYERED_PROJECT_API)
            .unwrap();
        test_dir
            .add_file("services/user_service.py", LAYERED_PROJECT_SERVICE)
            .unwrap();
        test_dir
            .add_file("utils/db.py", LAYERED_PROJECT_UTILS)
            .unwrap();

        // Create rules file
        let rules = r#"
version: "1.0"
layers:
  high: { directories: ["api/"] }
  middle: { directories: ["services/"] }
  low: { directories: ["utils/"] }
rules:
  - id: L1
    constraint: "LOW may not import HIGH"
    type: layer
    from_layers: [LOW]
    to_layers: [HIGH]
    severity: error
  - id: L2
    constraint: "MIDDLE may not import HIGH"
    type: layer
    from_layers: [MIDDLE]
    to_layers: [HIGH]
    severity: error
"#;
        test_dir.add_file("arch-rules.yaml", rules).unwrap();

        // Expected: check_rules passes with no violations
        // Valid flow: api -> services -> utils
        // let report = check_architecture_rules(test_dir.path(), "arch-rules.yaml").unwrap();
        //
        // assert!(report.pass);
        // assert!(report.violations.is_empty());
        // assert_eq!(report.summary.error_count, 0);

        todo!("Implement check_rules_allows_valid_dependencies test");
    }

    // -------------------------------------------------------------------------
    // Tarjan SCC Tests
    // -------------------------------------------------------------------------

    /// Test Tarjan algorithm finds simple 2-node cycle
    /// Contract: A -> B -> A is detected as single SCC
    #[test]
    #[ignore = "Tarjan SCC not yet implemented"]
    fn tarjan_finds_simple_cycle() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("cycles.py", SIMPLE_CYCLE).unwrap();

        // Expected: find exactly one SCC with 2 nodes
        // let graph = build_call_graph(test_dir.path(), Language::Python).unwrap();
        // let sccs = tarjan_scc(&graph);
        //
        // // Filter to SCCs with > 1 node (cycles)
        // let cycles: Vec<_> = sccs.iter().filter(|scc| scc.len() > 1).collect();
        //
        // assert_eq!(cycles.len(), 1);
        // assert_eq!(cycles[0].len(), 2);
        // assert!(cycles[0].contains(&"func_a".to_string()));
        // assert!(cycles[0].contains(&"func_b".to_string()));

        todo!("Implement tarjan_finds_simple_cycle test");
    }

    /// Test Tarjan algorithm finds complex 3+ node cycle
    /// Contract: A -> B -> C -> A is detected as single SCC
    #[test]
    #[ignore = "Tarjan SCC not yet implemented"]
    fn tarjan_finds_complex_scc() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("cycles.py", COMPLEX_CYCLE).unwrap();

        // Expected: find exactly one SCC with 3 nodes
        // let graph = build_call_graph(test_dir.path(), Language::Python).unwrap();
        // let sccs = tarjan_scc(&graph);
        //
        // let cycles: Vec<_> = sccs.iter().filter(|scc| scc.len() > 1).collect();
        //
        // assert_eq!(cycles.len(), 1);
        // assert_eq!(cycles[0].len(), 3);
        // assert!(cycles[0].contains(&"node_a".to_string()));
        // assert!(cycles[0].contains(&"node_b".to_string()));
        // assert!(cycles[0].contains(&"node_c".to_string()));

        todo!("Implement tarjan_finds_complex_scc test");
    }

    /// Test Tarjan algorithm correctly identifies multiple separate SCCs
    /// Contract: Two independent cycles are found as separate SCCs
    #[test]
    #[ignore = "Tarjan SCC not yet implemented"]
    fn tarjan_finds_multiple_sccs() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("cycles.py", MULTIPLE_SCCS).unwrap();

        // Expected: find 2 SCCs (cycle_a/b and loop_x/y/z)
        // let graph = build_call_graph(test_dir.path(), Language::Python).unwrap();
        // let sccs = tarjan_scc(&graph);
        //
        // let cycles: Vec<_> = sccs.iter().filter(|scc| scc.len() > 1).collect();
        //
        // assert_eq!(cycles.len(), 2);
        // // One SCC with 2 nodes, one with 3 nodes
        // let sizes: Vec<_> = cycles.iter().map(|c| c.len()).collect();
        // assert!(sizes.contains(&2));
        // assert!(sizes.contains(&3));

        todo!("Implement tarjan_finds_multiple_sccs test");
    }

    /// Test Tarjan algorithm has no false positives on DAG
    /// Contract: No cycles reported for directed acyclic graph
    #[test]
    #[ignore = "Tarjan SCC not yet implemented"]
    fn tarjan_no_false_positives() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("dag.py", DAG_NO_CYCLES).unwrap();

        // Expected: no SCCs with > 1 node
        // let graph = build_call_graph(test_dir.path(), Language::Python).unwrap();
        // let sccs = tarjan_scc(&graph);
        //
        // let cycles: Vec<_> = sccs.iter().filter(|scc| scc.len() > 1).collect();
        //
        // assert!(cycles.is_empty(), "DAG should have no cycles");

        todo!("Implement tarjan_no_false_positives test");
    }

    /// Test Tarjan SCC output schema
    /// Contract: Output includes nodes, edges, size, is_cycle fields
    #[test]
    #[ignore = "Tarjan SCC not yet implemented"]
    fn tarjan_output_schema() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("cycles.py", SIMPLE_CYCLE).unwrap();

        // Expected: CycleReport with proper schema
        // let report = detect_cycles(test_dir.path(), Language::Python, CycleGranularity::Function).unwrap();
        //
        // assert!(report.cycles.len() >= 1);
        //
        // let cycle = &report.cycles[0];
        // assert!(!cycle.nodes.is_empty());
        // assert!(!cycle.edges.is_empty());
        // assert!(cycle.size > 1);
        // assert!(cycle.is_cycle);
        //
        // // Verify summary
        // assert!(report.summary.total_sccs > 0);
        // assert!(report.summary.cycle_count > 0);
        // assert_eq!(report.summary.granularity, "function");

        todo!("Implement tarjan_output_schema test");
    }
}

// =============================================================================
// patterns Tests
// =============================================================================

#[cfg(test)]
mod patterns_tests {
    use super::fixtures::*;

    // -------------------------------------------------------------------------
    // Soft Delete Detection Tests
    // -------------------------------------------------------------------------

    /// Test detection of is_deleted boolean field
    /// Contract: Confidence >= 0.4 when is_deleted field found
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_is_deleted_field() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("models/user.py", PYTHON_SOFT_DELETE)
            .unwrap();

        // Expected: soft_delete pattern detected with high confidence
        // let report = detect_patterns(test_dir.path(), None).unwrap();
        //
        // assert!(report.soft_delete.detected);
        // assert!(report.soft_delete.confidence >= 0.4);
        // assert!(report.soft_delete.column_names.contains(&"is_deleted".to_string()));

        todo!("Implement detects_is_deleted_field test");
    }

    /// Test detection of deleted_at timestamp field
    /// Contract: Confidence >= 0.4 when deleted_at field found
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_deleted_at_timestamp() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("models/user.py", PYTHON_SOFT_DELETE)
            .unwrap();

        // Expected: deleted_at field detected
        // let report = detect_patterns(test_dir.path(), None).unwrap();
        //
        // assert!(report.soft_delete.column_names.contains(&"deleted_at".to_string()));
        // assert!(report.soft_delete.confidence >= 0.8); // Both fields = high confidence

        todo!("Implement detects_deleted_at_timestamp test");
    }

    // -------------------------------------------------------------------------
    // Error Handling Detection Tests
    // -------------------------------------------------------------------------

    /// Test detection of try/catch pattern
    /// Contract: try_catch pattern listed with confidence >= 0.3
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_try_catch_pattern() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("service.py", PYTHON_ERROR_HANDLING)
            .unwrap();

        // Expected: try_catch pattern detected
        // let report = detect_patterns(test_dir.path(), None).unwrap();
        //
        // assert!(report.error_handling.confidence >= 0.3);
        // assert!(report.error_handling.patterns.contains(&"try_catch".to_string()));

        todo!("Implement detects_try_catch_pattern test");
    }

    /// Test detection of Result<T, E> type usage in Rust
    /// Contract: result_type pattern listed with confidence >= 0.4
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_result_type_usage() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("lib.rs", RUST_ERROR_HANDLING).unwrap();

        // Expected: result_type pattern detected for Rust
        // let report = detect_patterns(test_dir.path(), Some(Language::Rust)).unwrap();
        //
        // assert!(report.error_handling.confidence >= 0.4);
        // assert!(report.error_handling.patterns.contains(&"result_type".to_string()));

        todo!("Implement detects_result_type_usage test");
    }

    /// Test detection of custom exception classes
    /// Contract: Exception types listed with evidence
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_custom_exceptions() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("service.py", PYTHON_ERROR_HANDLING)
            .unwrap();

        // Expected: custom exception classes detected
        // let report = detect_patterns(test_dir.path(), None).unwrap();
        //
        // assert!(report.error_handling.exception_types.contains(&"ValidationError".to_string()));
        // assert!(report.error_handling.exception_types.contains(&"NotFoundError".to_string()));

        todo!("Implement detects_custom_exceptions test");
    }

    // -------------------------------------------------------------------------
    // Naming Convention Detection Tests
    // -------------------------------------------------------------------------

    /// Test detection of snake_case function naming
    /// Contract: functions field shows "snake_case" for Python
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_snake_case_functions() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("service.py", PYTHON_NAMING).unwrap();

        // Expected: snake_case detected for functions
        // let report = detect_patterns(test_dir.path(), Some(Language::Python)).unwrap();
        //
        // assert_eq!(report.naming.functions, NamingConvention::SnakeCase);
        // assert!(report.naming.consistency_score >= 0.9);

        todo!("Implement detects_snake_case_functions test");
    }

    /// Test detection of PascalCase class naming
    /// Contract: classes field shows "PascalCase"
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_pascal_case_classes() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("service.py", PYTHON_NAMING).unwrap();

        // Expected: PascalCase detected for classes
        // let report = detect_patterns(test_dir.path(), None).unwrap();
        //
        // assert_eq!(report.naming.classes, NamingConvention::PascalCase);

        todo!("Implement detects_pascal_case_classes test");
    }

    /// Test detection of UPPER_SNAKE_CASE constants
    /// Contract: constants field shows "UPPER_SNAKE_CASE"
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_upper_snake_case_constants() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("service.py", PYTHON_NAMING).unwrap();

        // Expected: UPPER_SNAKE_CASE detected for constants
        // let report = detect_patterns(test_dir.path(), None).unwrap();
        //
        // assert_eq!(report.naming.constants, NamingConvention::UpperSnakeCase);

        todo!("Implement detects_upper_snake_case_constants test");
    }

    // -------------------------------------------------------------------------
    // Resource Management Detection Tests
    // -------------------------------------------------------------------------

    /// Test detection of Python context manager pattern
    /// Contract: context_manager pattern detected with __enter__/__exit__
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_context_manager() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("file_utils.py", PYTHON_CONTEXT_MANAGER)
            .unwrap();

        // Expected: context_manager pattern detected
        // let report = detect_patterns(test_dir.path(), Some(Language::Python)).unwrap();
        //
        // assert!(report.resource_management.confidence >= 0.5);
        // assert!(report.resource_management.patterns.contains(&"context_manager".to_string()));

        todo!("Implement detects_context_manager test");
    }

    /// Test detection of Go defer statement
    /// Contract: defer pattern detected
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_defer_statement() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("file.go", GO_DEFER).unwrap();

        // Expected: defer pattern detected for Go
        // let report = detect_patterns(test_dir.path(), Some(Language::Go)).unwrap();
        //
        // assert!(report.resource_management.patterns.contains(&"defer".to_string()));

        todo!("Implement detects_defer_statement test");
    }

    /// Test detection of Rust RAII/Drop pattern
    /// Contract: raii pattern detected with Drop impl
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn detects_raii_pattern() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("lib.rs", RUST_RAII).unwrap();

        // Expected: raii pattern detected for Rust
        // let report = detect_patterns(test_dir.path(), Some(Language::Rust)).unwrap();
        //
        // assert!(report.resource_management.patterns.contains(&"raii".to_string()));

        todo!("Implement detects_raii_pattern test");
    }

    // -------------------------------------------------------------------------
    // Multi-Language Detection Tests
    // -------------------------------------------------------------------------

    /// Test Python pattern detection
    /// Contract: Python-specific patterns detected (try/except, context manager)
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn python_patterns_detected() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("service.py", PYTHON_ERROR_HANDLING)
            .unwrap();
        test_dir
            .add_file("file_utils.py", PYTHON_CONTEXT_MANAGER)
            .unwrap();

        // Expected: Python-specific patterns
        // let report = detect_patterns(test_dir.path(), Some(Language::Python)).unwrap();
        //
        // // Python try/except
        // assert!(report.error_handling.patterns.contains(&"try_catch".to_string()));
        // // Python context manager
        // assert!(report.resource_management.patterns.contains(&"context_manager".to_string()));

        todo!("Implement python_patterns_detected test");
    }

    /// Test TypeScript pattern detection
    /// Contract: TypeScript-specific patterns detected (try/catch, interfaces)
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn typescript_patterns_detected() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("models.ts", TYPESCRIPT_SOFT_DELETE)
            .unwrap();
        test_dir.add_file("service.ts", TYPESCRIPT_NAMING).unwrap();

        // Expected: TypeScript-specific patterns
        // let report = detect_patterns(test_dir.path(), Some(Language::TypeScript)).unwrap();
        //
        // // TypeScript interfaces
        // assert!(report.soft_delete.detected);
        // // TypeScript naming (camelCase functions)
        // assert_eq!(report.naming.functions, NamingConvention::CamelCase);

        todo!("Implement typescript_patterns_detected test");
    }

    /// Test Go pattern detection
    /// Contract: Go-specific patterns detected (if err != nil, defer)
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn go_patterns_detected() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("main.go", GO_ERROR_HANDLING).unwrap();
        test_dir.add_file("file.go", GO_DEFER).unwrap();

        // Expected: Go-specific patterns
        // let report = detect_patterns(test_dir.path(), Some(Language::Go)).unwrap();
        //
        // // Go error handling (if err != nil)
        // assert!(report.error_handling.confidence >= 0.4);
        // // Go defer
        // assert!(report.resource_management.patterns.contains(&"defer".to_string()));

        todo!("Implement go_patterns_detected test");
    }

    /// Test Rust pattern detection
    /// Contract: Rust-specific patterns detected (Result, ?, RAII)
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn rust_patterns_detected() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("lib.rs", RUST_ERROR_HANDLING).unwrap();
        test_dir.add_file("file.rs", RUST_RAII).unwrap();

        // Expected: Rust-specific patterns
        // let report = detect_patterns(test_dir.path(), Some(Language::Rust)).unwrap();
        //
        // // Rust Result type
        // assert!(report.error_handling.patterns.contains(&"result_type".to_string()));
        // // Rust ? operator
        // assert!(report.error_handling.confidence >= 0.5);
        // // Rust RAII
        // assert!(report.resource_management.patterns.contains(&"raii".to_string()));

        todo!("Implement rust_patterns_detected test");
    }

    // -------------------------------------------------------------------------
    // Output Schema Tests
    // -------------------------------------------------------------------------

    /// Test that output includes metadata section
    /// Contract: files_analyzed, duration_ms, language_distribution present
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn output_includes_metadata() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("service.py", PYTHON_NAMING).unwrap();

        // Expected: metadata in output
        // let report = detect_patterns(test_dir.path(), None).unwrap();
        //
        // assert!(report.metadata.files_analyzed > 0);
        // assert!(report.metadata.duration_ms > 0);
        // assert!(!report.metadata.language_distribution.files_by_language.is_empty());

        todo!("Implement output_includes_metadata test");
    }

    /// Test that output includes LLM constraints
    /// Contract: constraints array with category, rule, confidence, priority
    #[test]
    #[ignore = "patterns command not yet implemented"]
    fn output_includes_constraints() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("service.py", PYTHON_NAMING).unwrap();

        // Expected: constraints generated from patterns
        // let report = detect_patterns(test_dir.path(), None).unwrap();
        //
        // assert!(!report.constraints.is_empty());
        // let constraint = &report.constraints[0];
        // assert!(!constraint.category.is_empty());
        // assert!(!constraint.rule.is_empty());
        // assert!(constraint.confidence > 0.0);
        // assert!(constraint.priority >= 1);

        todo!("Implement output_includes_constraints test");
    }
}

// =============================================================================
// inheritance Tests
// =============================================================================

#[cfg(test)]
mod inheritance_tests {
    use super::fixtures::*;
    use crate::inheritance::{extract_inheritance, InheritanceOptions};
    use crate::types::Language;

    // -------------------------------------------------------------------------
    // Class Extraction Tests
    // -------------------------------------------------------------------------

    /// Test Python class hierarchy extraction
    /// Contract: ClassDef nodes extracted with bases
    #[test]
    fn extracts_python_class_hierarchy() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        // Check Dog -> Mammal chain
        let dog = report
            .nodes
            .iter()
            .find(|n| n.name == "Dog")
            .expect("Dog class not found");
        assert!(dog.bases.contains(&"Mammal".to_string()));

        let mammal = report
            .nodes
            .iter()
            .find(|n| n.name == "Mammal")
            .expect("Mammal class not found");
        assert!(mammal.bases.contains(&"Animal".to_string()));

        // Animal extends ABC
        let animal = report
            .nodes
            .iter()
            .find(|n| n.name == "Animal")
            .expect("Animal class not found");
        assert!(animal.bases.contains(&"ABC".to_string()));
    }

    /// Test TypeScript class hierarchy extraction
    /// Contract: class/interface/abstract declarations extracted
    #[test]
    fn extracts_typescript_class_hierarchy() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("animals.ts", TYPESCRIPT_INHERITANCE)
            .unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::TypeScript), &options).unwrap();

        // Check Dog -> Mammal chain and implements Serializable
        let dog = report
            .nodes
            .iter()
            .find(|n| n.name == "Dog")
            .expect("Dog class not found");
        assert!(dog.bases.contains(&"Mammal".to_string()));
        assert!(dog.bases.contains(&"Serializable".to_string())); // implements

        // Serializable is an interface
        let serializable = report
            .nodes
            .iter()
            .find(|n| n.name == "Serializable")
            .expect("Serializable not found");
        assert_eq!(serializable.interface, Some(true));

        // Animal is abstract
        let animal = report
            .nodes
            .iter()
            .find(|n| n.name == "Animal")
            .expect("Animal not found");
        assert_eq!(animal.is_abstract, Some(true));
    }

    // -------------------------------------------------------------------------
    // Pattern Detection Tests
    // -------------------------------------------------------------------------

    /// Test ABC/Protocol detection in Python
    /// Contract: abstract=true for ABC inheritors, protocol=true for Protocol
    #[test]
    fn detects_abc_protocol() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        // Animal is abstract (inherits from ABC)
        let animal = report.nodes.iter().find(|n| n.name == "Animal").unwrap();
        assert_eq!(animal.is_abstract, Some(true));

        // Serializable is a protocol
        let serializable = report
            .nodes
            .iter()
            .find(|n| n.name == "Serializable")
            .unwrap();
        assert_eq!(serializable.protocol, Some(true));
    }

    /// Test mixin class detection
    /// Contract: mixin=true for classes ending in "Mixin" or used as secondary base
    #[test]
    fn detects_mixin_class() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("mixins.py", PYTHON_MIXIN).unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        // TimestampMixin is detected as mixin (name ends with Mixin)
        let timestamp_mixin = report
            .nodes
            .iter()
            .find(|n| n.name == "TimestampMixin")
            .unwrap();
        assert_eq!(timestamp_mixin.mixin, Some(true));

        // AuditMixin is detected as mixin
        let audit_mixin = report
            .nodes
            .iter()
            .find(|n| n.name == "AuditMixin")
            .unwrap();
        assert_eq!(audit_mixin.mixin, Some(true));

        // User uses both mixins
        let user = report.nodes.iter().find(|n| n.name == "User").unwrap();
        assert!(user.bases.contains(&"TimestampMixin".to_string()));
        assert!(user.bases.contains(&"AuditMixin".to_string()));
    }

    /// Test diamond inheritance detection
    /// Contract: diamonds array contains detected patterns with paths
    #[test]
    fn detects_diamond_inheritance() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("diamond.py", PYTHON_DIAMOND).unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        // Diamond inheritance should be detected
        assert!(
            !report.diamonds.is_empty(),
            "Expected diamond pattern to be detected"
        );
        let diamond = &report.diamonds[0];
        assert_eq!(diamond.class_name, "Diamond");
        assert_eq!(diamond.common_ancestor, "Base");
        assert_eq!(diamond.paths.len(), 2);
    }

    // -------------------------------------------------------------------------
    // External Base Resolution Tests
    // -------------------------------------------------------------------------

    /// Test that external base classes are marked correctly
    /// Contract: resolution field is "stdlib", "project", or "unresolved"
    #[test]
    fn marks_external_base_classes() {
        use crate::types::BaseResolution;

        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        // ABC should be stdlib
        let abc_edge = report
            .edges
            .iter()
            .find(|e| e.parent == "ABC")
            .expect("ABC edge not found");
        assert_eq!(abc_edge.resolution, BaseResolution::Stdlib);
        assert!(abc_edge.external);

        // Exception should be stdlib
        let exc_edge = report
            .edges
            .iter()
            .find(|e| e.parent == "Exception")
            .expect("Exception edge not found");
        assert_eq!(exc_edge.resolution, BaseResolution::Stdlib);
        assert!(exc_edge.external);

        // Mammal should be project
        let mammal_edge = report
            .edges
            .iter()
            .find(|e| e.parent == "Mammal" && e.child == "Dog")
            .expect("Mammal->Dog edge not found");
        assert_eq!(mammal_edge.resolution, BaseResolution::Project);
        assert!(!mammal_edge.external);
    }

    // -------------------------------------------------------------------------
    // Output Format Tests
    // -------------------------------------------------------------------------

    /// Test JSON output structure
    /// Contract: edges, nodes, roots, leaves, diamonds, count present
    #[test]
    fn json_output_structure() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        // Serialize to JSON and verify structure
        let json_str = serde_json::to_string(&report).unwrap();
        let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();

        assert!(json.get("edges").is_some());
        assert!(json.get("nodes").is_some());
        assert!(json.get("roots").is_some());
        assert!(json.get("leaves").is_some());
        assert!(json.get("count").is_some());
        assert!(json.get("languages").is_some());
    }

    /// Test DOT output is valid Graphviz format
    /// Contract: Output starts with "digraph", contains node and edge definitions
    #[test]
    fn dot_output_valid_graphviz() {
        use crate::inheritance::format_dot;

        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();
        let output = format_dot(&report);

        assert!(output.starts_with("digraph inheritance"));
        assert!(output.contains("rankdir=BT"));
        assert!(output.contains("->")); // Has edges
        assert!(output.contains("[label=")); // Has node labels

        // Abstract classes should have special styling
        assert!(output.contains("fillcolor=lightyellow") || output.contains("<<abstract>>"));
    }

    /// Test text output format (tree view)
    /// Contract: Hierarchical tree with proper indentation
    #[test]
    fn text_output_tree_format() {
        use crate::inheritance::format_text;

        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();
        let output = format_text(&report);

        // Debug print
        eprintln!("Text output:\n{}", output);
        eprintln!("Number of nodes: {}", report.nodes.len());

        assert!(output.contains("Inheritance Graph"));
        assert!(output.contains("Roots"));
        assert!(output.contains("Leaves"));
        assert!(output.contains("Hierarchy:"));
        // Tree structure should contain class names - either in roots/leaves or hierarchy
        assert!(
            report.nodes.iter().any(|n| n.name == "Animal"),
            "Animal not found in nodes"
        );
        assert!(
            report.nodes.iter().any(|n| n.name == "Mammal"),
            "Mammal not found in nodes"
        );
    }

    // -------------------------------------------------------------------------
    // Filter Tests
    // -------------------------------------------------------------------------

    /// Test --class filter exact match
    /// Contract: Only focused class + ancestors + descendants returned
    #[test]
    fn class_filter_exact_match() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions {
            class_filter: Some("Mammal".to_string()),
            ..Default::default()
        };
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        let names: Vec<_> = report.nodes.iter().map(|n| n.name.as_str()).collect();

        // Should include Mammal
        assert!(names.contains(&"Mammal"));
        // Should include ancestor (Animal)
        assert!(names.contains(&"Animal"));
        // Should include descendants (Dog, Cat)
        assert!(names.contains(&"Dog"));
        assert!(names.contains(&"Cat"));
        // MyException should NOT be included (unrelated)
        assert!(!names.contains(&"MyException"));
    }

    /// Test --class filter fuzzy matching suggestions
    /// Contract: When class not found, suggest similar names
    #[test]
    fn class_filter_fuzzy_suggestion() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions {
            class_filter: Some("Mamal".to_string()), // Typo
            ..Default::default()
        };
        let result = extract_inheritance(test_dir.path(), Some(Language::Python), &options);

        // Should return error with suggestions
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Did you mean") || err.to_string().contains("Mammal"));
    }

    /// Test --depth limit
    /// Contract: Traversal stops at specified depth
    #[test]
    fn depth_limit_works() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();

        let options = InheritanceOptions {
            class_filter: Some("Mammal".to_string()),
            depth: Some(1),
            ..Default::default()
        };
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        let names: Vec<_> = report.nodes.iter().map(|n| n.name.as_str()).collect();

        // Should include Mammal
        assert!(names.contains(&"Mammal"));
        // Should include direct parent (Animal)
        assert!(names.contains(&"Animal"));
        // Should include direct children (Dog, Cat)
        assert!(names.contains(&"Dog"));
        assert!(names.contains(&"Cat"));
        // ABC is depth 2 from Mammal (Mammal -> Animal -> ABC) - should NOT be included
        // Note: ABC is not in the project (it's stdlib), so it wouldn't be included anyway
    }

    // -------------------------------------------------------------------------
    // Edge Case Tests
    // -------------------------------------------------------------------------

    /// Test empty project
    /// Contract: Returns empty graph, no errors
    #[test]
    fn handles_empty_project() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("empty.py", "# No classes here\npass\n")
            .unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        assert!(report.nodes.is_empty());
        assert!(report.edges.is_empty());
        assert_eq!(report.count, 0);
    }

    /// Test single class with no inheritance
    /// Contract: Class appears in nodes, no edges
    #[test]
    fn handles_single_class() {
        let test_dir = TestDir::new().unwrap();
        test_dir
            .add_file("single.py", "class Standalone:\n    pass\n")
            .unwrap();

        let options = InheritanceOptions::default();
        let report =
            extract_inheritance(test_dir.path(), Some(Language::Python), &options).unwrap();

        assert_eq!(report.nodes.len(), 1);
        let names: Vec<_> = report.nodes.iter().map(|n| n.name.as_str()).collect();
        assert!(names.contains(&"Standalone"));
        // No edges since no inheritance
        // Note: edges may include external bases if the class inherits from nothing
        assert!(report.roots.contains(&"Standalone".to_string()));
        assert!(report.leaves.contains(&"Standalone".to_string()));
    }

    /// Test multi-language project
    /// Contract: Both Python and TypeScript classes extracted
    #[test]
    fn handles_multi_language() {
        let test_dir = TestDir::new().unwrap();
        test_dir.add_file("animals.py", PYTHON_INHERITANCE).unwrap();
        test_dir
            .add_file("models.ts", TYPESCRIPT_INHERITANCE)
            .unwrap();

        // No language filter - extract from both
        let options = InheritanceOptions::default();
        let report = extract_inheritance(test_dir.path(), None, &options).unwrap();

        let names: Vec<_> = report.nodes.iter().map(|n| n.name.as_str()).collect();

        // Python classes
        assert!(names.contains(&"Animal"));
        // TypeScript classes (Serializable is an interface)
        assert!(names.contains(&"Serializable"));
        // Languages tracked
        assert!(report.languages.contains(&Language::Python));
        assert!(report.languages.contains(&Language::TypeScript));
    }
}