Spaces:
Sleeping

File size: 47,018 Bytes
aa0f1ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6531129
35db415
 
 
 
 
 
 
 
 
 
6531129
 
 
 
 
35db415
 
6996241
35db415
 
 
6996241
 
 
 
 
 
 
 
 
35db415
 
 
 
 
6996241
 
 
 
 
 
 
 
35db415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6531129
 
 
 
 
aa0f1ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a87217c
aa0f1ab
 
 
 
 
 
 
 
a87217c
 
aa0f1ab
a87217c
aa0f1ab
 
a87217c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa0f1ab
 
a87217c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa0f1ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a87217c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa0f1ab
a87217c
 
 
aa0f1ab
 
a87217c
 
 
 
 
 
 
 
 
 
 
 
 
aa0f1ab
 
 
 
 
 
 
 
 
 
 
35db415
 
 
 
 
aa0f1ab
 
 
 
6996241
 
 
 
 
aa0f1ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6531129
aa0f1ab
 
6531129
aa0f1ab
 
 
 
 
 
 
 
 
 
 
 
6531129
 
 
 
 
 
 
 
 
 
 
aa0f1ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35db415
 
 
 
 
 
 
6996241
 
 
35db415
 
 
aa0f1ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8f40ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa0f1ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Network Loader Module (network_loader.py)
Loads LinkedIn Connection Data CSV with movement tracking.

Expected CSV Columns:
    - Owner: Colleague who owns the connection (e.g., 'Adam', 'Adela')
    - Full Name: Contact's full name
    - Company: Current company
    - Position: Current position/title
    - New Company?: 'Y' or 'N' - indicates if contact moved companies
    - New Position?: 'Y' or 'N' - indicates if contact changed roles
    - Date Connected: When the connection was made (optional)

Usage:
    python network_loader.py                           # Load CSV
    python network_loader.py --file custom.csv         # Load custom file
    python network_loader.py --match "Premier Foods"   # Find connections
    python network_loader.py --movers                  # Show movers alert
    python network_loader.py --stats                   # Network statistics
"""

import os
import csv
import sqlite3
import re
from datetime import datetime
from typing import Optional
from dataclasses import dataclass
from enum import Enum

# Try to import fuzzy matching
try:
    from rapidfuzz import fuzz, process
    FUZZY_AVAILABLE = True
except ImportError:
    FUZZY_AVAILABLE = False
    print("Warning: rapidfuzz not installed. Install with: pip install rapidfuzz")

DATABASE = "leads.db"
DEFAULT_CSV_FILE = "data/my_team_connections.csv"


def convert_xlsx_to_csv(xlsx_path: str) -> str:
    """Convert an XLSX file to CSV format, returning the CSV path.

    The team's master workbook contains many sheets (pivot tables, dropdowns,
    message templates, etc.). `wb.active` returns whichever sheet was active
    when the file was last saved β€” often *not* the data sheet. Instead, scan
    every sheet, find those whose first ~15 rows contain the connection-data
    header signature (Company + Position, plus either Owner/Full Name or
    First Name + Last Name), and pick the largest match. Falls back to
    `wb.active` if nothing looks like data.
    """
    import openpyxl

    csv_path = xlsx_path.rsplit('.', 1)[0] + '.csv'
    wb = openpyxl.load_workbook(xlsx_path, read_only=True, data_only=True)

    REQUIRED_TOKENS = {"company", "position"}
    NAME_TOKENS = {"full name", "first name", "last name", "owner", "name"}
    MOVEMENT_TOKENS = {"position change?", "company change?", "new position?", "new company?"}

    def _sheet_score(ws) -> tuple[int, int, int] | None:
        """Return (priority, header_row_idx, n_rows) if sheet looks like
        connection data; None otherwise. Higher priority = preferred.

        Priority tiers (most preferred last):
          0 β€” connection data, no Owner
          1 β€” connection data with Owner
          2 β€” connection data with Owner AND movement tracking
              (Position Change? / Company Change?). The team's "New Data"
              sheet has these and drives MOVERS/PROMOTED signals.
        """
        try:
            for header_idx, row in enumerate(ws.iter_rows(values_only=True, max_row=15)):
                cells = {str(c).strip().lower() for c in row if c is not None}
                if REQUIRED_TOKENS.issubset(cells) and (cells & NAME_TOKENS):
                    has_owner = "owner" in cells
                    has_movement = bool(cells & MOVEMENT_TOKENS)
                    if has_owner and has_movement:
                        priority = 2
                    elif has_owner:
                        priority = 1
                    else:
                        priority = 0
                    return (priority, header_idx, ws.max_row or 0)
        except Exception:
            return None
        return None

    best = None  # (priority, n_rows, header_idx, sheet_name)
    for sn in wb.sheetnames:
        ws = wb[sn]
        info = _sheet_score(ws)
        if info is None:
            continue
        priority, header_idx, n_rows = info
        candidate = (priority, n_rows, header_idx, sn)
        if best is None or candidate > best:
            best = candidate

    if best is not None:
        _, _, header_idx, sheet_name = best
        ws = wb[sheet_name]
        with open(csv_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            for i, row in enumerate(ws.iter_rows(values_only=True)):
                if i < header_idx:
                    continue  # skip preamble before header row
                writer.writerow([cell if cell is not None else '' for cell in row])
    else:
        # Fallback: dump active sheet as before
        ws = wb.active
        with open(csv_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            for row in ws.iter_rows(values_only=True):
                writer.writerow([cell if cell is not None else '' for cell in row])

    wb.close()
    return csv_path


# =============================================================================
# DATA MODELS
# =============================================================================

class ConnectionTier(Enum):
    """Connection strength tiers."""
    TIER_1_EXACT_ROLE = 1      # Direct connection to target role
    TIER_2_SENIOR = 2          # C-Suite/Director level connection
    TIER_3_COMPANY = 3         # Any connection at company
    NO_CONNECTION = 99         # No connection found


class ContactStatus(Enum):
    """Contact status flags."""
    ACTIVE = "ACTIVE"
    MOVER = "MOVER"           # Changed companies
    PROMOTED = "PROMOTED"     # New position at same company


@dataclass
class ConnectionMatch:
    """Represents a matched connection."""
    name: str
    company: str
    position: str
    colleague: str
    tier: ConnectionTier
    match_score: float
    is_senior: bool
    is_mover: bool = False
    role_match_score: float = 0.0

    @property
    def tier_emoji(self) -> str:
        return {
            ConnectionTier.TIER_1_EXACT_ROLE: "🎯",
            ConnectionTier.TIER_2_SENIOR: "⭐",
            ConnectionTier.TIER_3_COMPANY: "πŸ”—",
            ConnectionTier.NO_CONNECTION: "❄️"
        }.get(self.tier, "")

    @property
    def tier_label(self) -> str:
        return {
            ConnectionTier.TIER_1_EXACT_ROLE: "DIRECT HIT",
            ConnectionTier.TIER_2_SENIOR: "SENIOR CONNECTION",
            ConnectionTier.TIER_3_COMPANY: "COMPANY CONNECTION",
            ConnectionTier.NO_CONNECTION: "NO CONNECTION"
        }.get(self.tier, "")


@dataclass
class NetworkHit:
    """Represents a network intelligence result."""
    company: str
    target_role: Optional[str]
    matches: list[ConnectionMatch]
    best_match: Optional[ConnectionMatch]
    tier: ConnectionTier
    total_connections: int

    @property
    def has_connection(self) -> bool:
        return self.tier != ConnectionTier.NO_CONNECTION

    @property
    def summary(self) -> str:
        if not self.has_connection:
            return f"❄️ No connections found at {self.company}"

        if self.best_match:
            bm = self.best_match
            mover_flag = " πŸš€ MOVER" if bm.is_mover else ""
            if self.tier == ConnectionTier.TIER_1_EXACT_ROLE:
                return f"🎯 DIRECT HIT: {bm.colleague} knows {bm.name} ({bm.position}) at {self.company}!{mover_flag}"
            elif self.tier == ConnectionTier.TIER_2_SENIOR:
                return f"⭐ SENIOR: {bm.colleague} knows {bm.name} ({bm.position}) at {self.company}{mover_flag}"
            else:
                if self.total_connections > 1:
                    return f"πŸ”— {self.total_connections} connections at {self.company} (best: {bm.colleague} β†’ {bm.name})"
                return f"πŸ”— {bm.colleague} knows {bm.name} ({bm.position}) at {self.company}{mover_flag}"

        return f"πŸ”— {self.total_connections} connection(s) at {self.company}"


@dataclass
class Mover:
    """Represents a contact who moved companies."""
    name: str
    colleague: str
    company: str
    position: str
    is_new_position: bool
    date_connected: str

    @property
    def alert_text(self) -> str:
        position_change = " (new role!)" if self.is_new_position else ""
        return f"πŸš€ {self.name} (known by {self.colleague}) just moved to {self.company} as {self.position}{position_change}"


# =============================================================================
# COMPANY NAME NORMALIZATION
# =============================================================================

COMPANY_SUFFIXES = [
    r'\s+plc\.?$', r'\s+ltd\.?$', r'\s+limited$', r'\s+inc\.?$',
    r'\s+incorporated$', r'\s+corp\.?$', r'\s+corporation$',
    r'\s+llc$', r'\s+llp$', r'\s+group$', r'\s+holdings$',
    r'\s+uk$', r'\s+international$', r'\s+&\s+co\.?$',
    r'\s+and\s+co\.?$', r'\s+partners$', r'\s+consulting$',
    r'\s+services$', r'\s+solutions$', r'\(uk\)$', r'\(united kingdom\)$',
]

SENIOR_TITLES = [
    # C-Suite
    'ceo', 'chief executive', 'chief executive officer',
    'cfo', 'chief financial', 'chief financial officer',
    'coo', 'chief operating', 'chief operating officer',
    'cto', 'chief technology', 'chief technology officer',
    'cmo', 'chief marketing', 'chief marketing officer',
    'cio', 'chief information', 'chief information officer',
    'chro', 'chief human resources', 'chief people', 'chief people officer',
    'cpo', 'chief product', 'cro', 'chief revenue',
    'chief transformation', 'chief culture', 'chief digital',
    # Director level
    'director', 'managing director', 'md',
    # VP / President
    'vp', 'vice president', 'vice-president',
    'president', 'chairman', 'chairwoman', 'chair',
    # Partner / Head
    'partner', 'head of', 'global head', 'regional head',
    # General management
    'general manager', 'gm',
    # Programme / transformation leadership
    'programme director', 'program director',
    'head of transformation', 'transformation director',
    'head of change', 'director of change',
    'head of people', 'director of people',
    'head of hr', 'director of hr',
    'head of organisational', 'director of organisational',
    'head of strategy', 'director of strategy',
    'head of operations', 'director of operations',
    'head of digital', 'director of digital',
    'head of technology', 'director of technology',
    'head of finance', 'director of finance',
    'head of pmo', 'portfolio director',
    # Senior individual contributors (but NOT "senior analyst", "senior assistant" etc.)
    'principal consultant', 'principal advisor',
    # Council-specific
    'chief executive', 'deputy chief executive',
    'director of resources', 'director of people',
    's151 officer', 'monitoring officer',
]

# Titles that should NEVER be surfaced as the recommended contact β€”
# regardless of is_senior flag or recency. These are support/admin/
# junior roles that a partner should not be cold-approaching.
EXCLUDED_CONTACT_TITLES = [
    'assistant', 'administrator', 'coordinator', 'receptionist',
    'intern', 'apprentice', 'graduate', 'trainee', 'junior',
    'analyst',  # too broad on its own β€” "senior analyst" is fine but plain "analyst" is not
    'support',  # "HR Support", "IT Support"
    'executive assistant',  # EA is admin, not executive
    'personal assistant', 'pa to',
    'officer',  # generic β€” "HR Officer", "Finance Officer" etc. (too junior)
    'specialist',  # often mid-level; "HR Specialist" is not a decision-maker
    'advisor',  # on its own too junior; "Senior Advisor" is fine
    'associate',  # consulting junior grade
]


def is_excluded_contact(position: str) -> bool:
    """True if this title should be filtered OUT of digest contact recommendations.
    More conservative than is_senior β€” we'd rather show no contact than a junior one."""
    if not position:
        return False
    pos = position.lower()
    # Never exclude if a seniority qualifier is present
    if any(q in pos for q in ('senior ', 'lead ', 'head ', 'chief ', 'director',
                               'vp ', 'principal ', 'managing ')):
        return False
    return any(excl in pos for excl in EXCLUDED_CONTACT_TITLES)


def normalize_company(company: str) -> str:
    """Normalize company name for matching."""
    if not company:
        return ""
    name = company.lower().strip()
    for suffix in COMPANY_SUFFIXES:
        name = re.sub(suffix, '', name, flags=re.IGNORECASE)
    name = re.sub(r'[^\w\s]', ' ', name)
    name = ' '.join(name.split())
    return name.strip()


def is_senior_position(position: str) -> bool:
    """Check if a position is C-Suite or Director level."""
    if not position:
        return False
    pos_lower = position.lower()
    for title in SENIOR_TITLES:
        if title in pos_lower:
            return True
    return False


def match_role(target_role: str, actual_position: str) -> float:
    """Calculate how well a position matches a target role (0-100)."""
    if not target_role or not actual_position:
        return 0.0
    target = target_role.lower().strip()
    actual = actual_position.lower().strip()
    if target == actual:
        return 100.0

    target_words = set(target.split()) - {'of', 'the', 'and', 'at', 'for', 'in', 'a', 'an'}
    actual_words = set(actual.split()) - {'of', 'the', 'and', 'at', 'for', 'in', 'a', 'an'}

    if target_words and actual_words:
        overlap = len(target_words & actual_words)
        max_words = max(len(target_words), len(actual_words))
        word_score = (overlap / max_words) * 100 if max_words > 0 else 0
    else:
        word_score = 0

    if FUZZY_AVAILABLE:
        fuzzy_score = fuzz.token_sort_ratio(target, actual)
        return max(word_score, fuzzy_score)
    return word_score


# =============================================================================
# DATABASE OPERATIONS
# =============================================================================

def get_connection():
    """Create database connection."""
    return sqlite3.connect(DATABASE)


def init_network_tables():
    """Initialize network database tables, handling schema migration."""
    conn = get_connection()
    cursor = conn.cursor()

    # Check if old schema exists (from ingest_networks.py)
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='network_graph'")
    table_exists = cursor.fetchone() is not None

    if table_exists:
        # Check columns to see which schema we have
        cursor.execute("PRAGMA table_info(network_graph)")
        columns = {row[1] for row in cursor.fetchall()}

        # Old schema has 'connection_name', new schema has 'contact_name'
        if 'connection_name' in columns and 'contact_name' not in columns:
            # Migrate from old schema to new schema
            print("Migrating network_graph from old schema...")

            # Create new table
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS network_graph_new (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    colleague_owner TEXT NOT NULL,
                    contact_name TEXT NOT NULL,
                    company TEXT,
                    company_normalized TEXT,
                    position TEXT,
                    date_connected TEXT,
                    is_senior INTEGER DEFAULT 0,
                    status TEXT DEFAULT 'ACTIVE',
                    is_new_company INTEGER DEFAULT 0,
                    is_new_position INTEGER DEFAULT 0,
                    source_file TEXT,
                    date_imported TEXT NOT NULL
                )
            """)

            # Migrate data
            cursor.execute("""
                INSERT INTO network_graph_new (
                    colleague_owner, contact_name, company, company_normalized,
                    position, date_connected, is_senior, status,
                    is_new_company, is_new_position, source_file, date_imported
                )
                SELECT
                    COALESCE(source_colleague, 'Unknown'),
                    connection_name,
                    connection_company,
                    connection_company_normalized,
                    connection_title,
                    connected_on,
                    COALESCE(is_senior, 0),
                    'ACTIVE',
                    0,
                    0,
                    source_file,
                    COALESCE(date_imported, datetime('now'))
                FROM network_graph
            """)

            # Swap tables
            cursor.execute("DROP TABLE network_graph")
            cursor.execute("ALTER TABLE network_graph_new RENAME TO network_graph")
            print("Migration complete!")

        # Add missing columns if needed (for partial migrations)
        if 'status' not in columns:
            try:
                cursor.execute("ALTER TABLE network_graph ADD COLUMN status TEXT DEFAULT 'ACTIVE'")
            except:
                pass
        if 'is_new_company' not in columns:
            try:
                cursor.execute("ALTER TABLE network_graph ADD COLUMN is_new_company INTEGER DEFAULT 0")
            except:
                pass
        if 'is_new_position' not in columns:
            try:
                cursor.execute("ALTER TABLE network_graph ADD COLUMN is_new_position INTEGER DEFAULT 0")
            except:
                pass

    else:
        # Create fresh table with new schema
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS network_graph (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                colleague_owner TEXT NOT NULL,
                contact_name TEXT NOT NULL,
                company TEXT,
                company_normalized TEXT,
                position TEXT,
                date_connected TEXT,
                is_senior INTEGER DEFAULT 0,
                status TEXT DEFAULT 'ACTIVE',
                is_new_company INTEGER DEFAULT 0,
                is_new_position INTEGER DEFAULT 0,
                source_file TEXT,
                date_imported TEXT NOT NULL,
                UNIQUE(contact_name, company, colleague_owner)
            )
        """)

    # Create indexes (safe to run multiple times)
    try:
        cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_company_norm ON network_graph(company_normalized)")
    except:
        pass
    try:
        cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_colleague ON network_graph(colleague_owner)")
    except:
        pass
    try:
        cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_status ON network_graph(status)")
    except:
        pass
    try:
        cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_movers ON network_graph(is_new_company)")
    except:
        pass

    # Team members table
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS team_members (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT UNIQUE NOT NULL,
            connections_count INTEGER DEFAULT 0,
            movers_count INTEGER DEFAULT 0,
            last_import TEXT
        )
    """)

    conn.commit()
    conn.close()


def get_preserved_owners() -> list:
    """Owners whose connections survive a clear-and-reload.

    Some valuable networks are no longer in the team's master export β€” e.g.
    a colleague who has left but whose relationships we still have access
    to. Without this, a clear_existing reload (the app's upload path always
    uses one) would silently delete them, and the data is unrecoverable
    from the new sheet. Configured in config.yaml > network_preserve_owners.
    """
    try:
        import yaml
        cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.yaml")
        with open(cfg_path, "r", encoding="utf-8") as f:
            cfg = yaml.safe_load(f) or {}
        return [str(o).strip() for o in (cfg.get("network_preserve_owners") or []) if str(o).strip()]
    except Exception:
        return []


def clear_network_data():
    """Clear network data, keeping any owners listed in
    config.yaml > network_preserve_owners (see get_preserved_owners)."""
    preserved = get_preserved_owners()
    conn = get_connection()
    cursor = conn.cursor()
    if preserved:
        placeholders = ",".join("?" * len(preserved))
        cursor.execute(
            f"DELETE FROM network_graph WHERE colleague_owner NOT IN ({placeholders})",
            preserved,
        )
        cursor.execute(
            f"DELETE FROM team_members WHERE name NOT IN ({placeholders})",
            preserved,
        )
    else:
        cursor.execute("DELETE FROM network_graph")
        cursor.execute("DELETE FROM team_members")
    conn.commit()
    conn.close()


# =============================================================================
# CSV LOADING
# =============================================================================

# Column name variations we accept
COLUMN_MAPPINGS = {
    'owner': ['Owner', 'owner', 'Colleague', 'Team Member', 'Connected To', 'Source'],
    # NOTE: 'First Name' deliberately excluded β€” when only First/Last Name
    # exist (no combined Full Name column), the loader combines them via the
    # firstname/lastname branch. Including 'First Name' here would short-
    # circuit that and store first-name-only as the contact name.
    'full_name': ['Full Name', 'FullName', 'Name', 'Contact Name'],
    'first_name': ['First Name', 'FirstName', 'first_name'],
    'last_name': ['Last Name', 'LastName', 'last_name'],
    'company': ['Company', 'company', 'Organization', 'Organisation', 'Employer'],
    'position': ['Position', 'position', 'Title', 'Job Title', 'Role'],
    # Order matters: flag-style columns first. The team's master sheet has
    # both 'Position Change?' (Y/N flag) and 'New Position' (text β€” the new
    # role title); we want the flag, never the text column.
    'new_company': ['Company Change?', 'New Company?', 'NewCompany', 'Company Changed', 'Moved'],
    'new_position': ['Position Change?', 'New Position?', 'NewPosition', 'Role Changed', 'Promoted'],
    'date_connected': ['Date Connected', 'Connected On', 'Connection Date', 'Date'],
}


def find_column(headers: list, column_type: str) -> Optional[str]:
    """Find the actual column name from headers."""
    possible_names = COLUMN_MAPPINGS.get(column_type, [])
    for name in possible_names:
        if name in headers:
            return name
    return None


def is_yes(value: str) -> bool:
    """Check if a value represents 'Yes'."""
    if not value:
        return False
    return value.strip().upper() in ['Y', 'YES', 'TRUE', '1', 'X']


def load_csv(filepath: str = DEFAULT_CSV_FILE, clear_existing: bool = False) -> dict:
    """
    Load the LinkedIn Connection Data from CSV or XLSX.

    Args:
        filepath: Path to the CSV or XLSX file
        clear_existing: If True, clear existing data before loading

    Returns:
        Dict with import statistics
    """
    if not os.path.exists(filepath):
        return {
            'success': False,
            'error': f'File not found: {filepath}',
            'imported': 0
        }

    # Convert XLSX to CSV if needed
    if filepath.lower().endswith('.xlsx'):
        try:
            filepath = convert_xlsx_to_csv(filepath)
        except Exception as e:
            return {
                'success': False,
                'error': f'XLSX conversion failed: {e}',
                'imported': 0
            }

    init_network_tables()

    if clear_existing:
        clear_network_data()

    stats = {
        'success': True,
        'file': filepath,
        'total_rows': 0,
        'imported': 0,
        'skipped': 0,
        'errors': 0,
        'movers': 0,
        'promoted': 0,
        'colleagues': set(),
    }

    conn = get_connection()
    cursor = conn.cursor()

    try:
        for encoding in ['utf-8', 'utf-8-sig', 'latin-1', 'cp1252']:
            try:
                with open(filepath, 'r', encoding=encoding) as f:
                    content = f.read()
                    lines = content.split('\n')

                    # Find header row
                    header_idx = 0
                    for i, line in enumerate(lines[:10]):
                        if any(col in line for col in ['Owner', 'Full Name', 'Company', 'Position']):
                            header_idx = i
                            break

                    f.seek(0)
                    for _ in range(header_idx):
                        f.readline()

                    reader = csv.DictReader(f)
                    headers = reader.fieldnames or []

                    # Find column mappings
                    owner_col = find_column(headers, 'owner')
                    fullname_col = find_column(headers, 'full_name')
                    firstname_col = find_column(headers, 'first_name')
                    lastname_col = find_column(headers, 'last_name')
                    company_col = find_column(headers, 'company')
                    position_col = find_column(headers, 'position')
                    new_company_col = find_column(headers, 'new_company')
                    new_position_col = find_column(headers, 'new_position')
                    date_col = find_column(headers, 'date_connected')

                    stats['detected_columns'] = {
                        'owner': owner_col,
                        'full_name': fullname_col,
                        'first_name': firstname_col,
                        'last_name': lastname_col,
                        'company': company_col,
                        'position': position_col,
                        'new_company_flag': new_company_col,
                        'new_position_flag': new_position_col,
                        'date_connected': date_col,
                    }
                    stats['headers'] = list(headers)

                    for row in reader:
                        stats['total_rows'] += 1

                        try:
                            # Extract owner
                            owner = row.get(owner_col, '').strip() if owner_col else 'Unknown'

                            # Extract name
                            if fullname_col:
                                contact_name = row.get(fullname_col, '').strip()
                            else:
                                first = row.get(firstname_col, '').strip() if firstname_col else ''
                                last = row.get(lastname_col, '').strip() if lastname_col else ''
                                contact_name = f"{first} {last}".strip()

                            company = row.get(company_col, '').strip() if company_col else ''
                            position = row.get(position_col, '').strip() if position_col else ''
                            date_connected = row.get(date_col, '').strip() if date_col else ''

                            # Movement tracking
                            is_new_company = is_yes(row.get(new_company_col, '')) if new_company_col else False
                            is_new_position = is_yes(row.get(new_position_col, '')) if new_position_col else False

                            # Skip if no name
                            if not contact_name:
                                stats['skipped'] += 1
                                continue

                            # Determine status
                            if is_new_company:
                                status = 'MOVER'
                                stats['movers'] += 1
                            elif is_new_position:
                                status = 'PROMOTED'
                                stats['promoted'] += 1
                            else:
                                status = 'ACTIVE'

                            company_normalized = normalize_company(company)
                            is_senior = 1 if is_senior_position(position) else 0

                            stats['colleagues'].add(owner)

                            cursor.execute("""
                                INSERT OR REPLACE INTO network_graph (
                                    colleague_owner, contact_name, company, company_normalized,
                                    position, date_connected, is_senior, status,
                                    is_new_company, is_new_position, source_file, date_imported
                                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                            """, (
                                owner, contact_name, company, company_normalized,
                                position, date_connected, is_senior, status,
                                1 if is_new_company else 0,
                                1 if is_new_position else 0,
                                filepath, datetime.now().isoformat()
                            ))

                            stats['imported'] += 1

                        except Exception as e:
                            stats['errors'] += 1

                    break

            except UnicodeDecodeError:
                continue

        conn.commit()

        # Update team members
        for colleague in stats['colleagues']:
            cursor.execute("SELECT COUNT(*) FROM network_graph WHERE colleague_owner = ?", (colleague,))
            count = cursor.fetchone()[0]
            cursor.execute("SELECT COUNT(*) FROM network_graph WHERE colleague_owner = ? AND is_new_company = 1", (colleague,))
            movers = cursor.fetchone()[0]

            cursor.execute("""
                INSERT OR REPLACE INTO team_members (name, connections_count, movers_count, last_import)
                VALUES (?, ?, ?, ?)
            """, (colleague, count, movers, datetime.now().isoformat()))

        conn.commit()
        stats['colleagues'] = list(stats['colleagues'])

    except Exception as e:
        stats['success'] = False
        stats['error'] = str(e)

    finally:
        conn.close()

    return stats


# Alias for backwards compatibility
load_master_csv = load_csv


# =============================================================================
# MATCHING ENGINE
# =============================================================================

def find_network_hit(
    company: str,
    target_role: str = None,
    min_company_score: int = 75,
    min_role_score: int = 60
) -> NetworkHit:
    """Find network connections at a company with tiered matching."""
    if not company:
        return NetworkHit(
            company=company, target_role=target_role, matches=[],
            best_match=None, tier=ConnectionTier.NO_CONNECTION, total_connections=0
        )

    conn = get_connection()
    cursor = conn.cursor()
    target_normalized = normalize_company(company)

    cursor.execute("""
        SELECT contact_name, company, company_normalized, position,
               colleague_owner, is_senior, is_new_company
        FROM network_graph
    """)

    rows = cursor.fetchall()
    conn.close()

    matches = []

    for row in rows:
        name, orig_company, norm_company, position, colleague, is_senior, is_mover = row

        if FUZZY_AVAILABLE:
            company_score = max(
                fuzz.ratio(target_normalized, norm_company or ''),
                fuzz.partial_ratio(target_normalized, norm_company or ''),
                fuzz.token_sort_ratio(target_normalized, norm_company or '')
            )
        else:
            company_score = 100 if target_normalized in (norm_company or '') or (norm_company or '') in target_normalized else 0

        if company_score < min_company_score:
            continue

        role_score = match_role(target_role, position) if target_role else 0.0

        if target_role and role_score >= min_role_score:
            tier = ConnectionTier.TIER_1_EXACT_ROLE
        elif is_senior:
            tier = ConnectionTier.TIER_2_SENIOR
        else:
            tier = ConnectionTier.TIER_3_COMPANY

        match = ConnectionMatch(
            name=name, company=orig_company or '', position=position or "Unknown",
            colleague=colleague, tier=tier, match_score=company_score,
            is_senior=bool(is_senior), is_mover=bool(is_mover), role_match_score=role_score
        )
        matches.append(match)

    matches.sort(key=lambda m: (m.tier.value, -m.match_score, -m.role_match_score))

    if not matches:
        return NetworkHit(
            company=company, target_role=target_role, matches=[],
            best_match=None, tier=ConnectionTier.NO_CONNECTION, total_connections=0
        )

    return NetworkHit(
        company=company, target_role=target_role, matches=matches,
        best_match=matches[0], tier=matches[0].tier, total_connections=len(matches)
    )


# =============================================================================
# SERVICE-AFFINITY ROUTING
# =============================================================================

# Team member specialisations (loaded from config at runtime, with fallback)
_TEAM_SERVICE_FOCUS = None

def _get_team_service_focus() -> dict:
    """Load team member service focus from config.yaml (cached)."""
    global _TEAM_SERVICE_FOCUS
    if _TEAM_SERVICE_FOCUS is not None:
        return _TEAM_SERVICE_FOCUS

    try:
        import yaml
        with open('config.yaml', 'r') as f:
            config = yaml.safe_load(f)
        team = config.get('team', [])
        _TEAM_SERVICE_FOCUS = {
            m['name'].lower(): m.get('service_focus', [])
            for m in team
        }
    except Exception:
        _TEAM_SERVICE_FOCUS = {
            'piers lyon': ['transformation_delivery', 'culture_capability'],
            'adam': ['transformation_delivery'],
            'stuart': ['culture_capability'],
        }
    return _TEAM_SERVICE_FOCUS


def find_network_hit_with_affinity(
    company: str,
    target_role: str = None,
    dominant_service: str = None,
    td_score: int = 0,
    cc_score: int = 0,
    min_company_score: int = 75,
    min_role_score: int = 60,
) -> 'NetworkHit':
    """Enhanced network routing that considers colleague service specialisation.

    When multiple colleagues have connections at the same company, prefer
    the colleague whose service_focus matches the company's dominant need.

    Args:
        company: Target company name
        target_role: Optional target role/position
        dominant_service: 'transformation_delivery' or 'culture_capability' (explicit)
        td_score: Company's TD score (used to infer dominant service if not explicit)
        cc_score: Company's CC score (used to infer dominant service if not explicit)
    """
    # Get base matches
    hit = find_network_hit(company, target_role, min_company_score, min_role_score)

    if not hit.has_connection or len(hit.matches) <= 1:
        return hit  # No routing decision needed

    # Determine dominant service need
    if not dominant_service:
        if td_score > cc_score + 10:
            dominant_service = 'transformation_delivery'
        elif cc_score > td_score + 10:
            dominant_service = 'culture_capability'
        else:
            return hit  # Scores are close, no strong affinity preference

    team_focus = _get_team_service_focus()

    # Re-sort matches: prefer colleagues whose service_focus includes the dominant service
    def affinity_sort_key(m: ConnectionMatch):
        colleague_lower = (m.colleague or '').lower()
        focus = team_focus.get(colleague_lower, [])
        has_affinity = 1 if dominant_service in focus else 0
        # Primary: tier (lower = better), Secondary: affinity (1 = better), Tertiary: match_score
        return (m.tier.value, -has_affinity, -m.match_score, -m.role_match_score)

    sorted_matches = sorted(hit.matches, key=affinity_sort_key)

    return NetworkHit(
        company=company,
        target_role=target_role,
        matches=sorted_matches,
        best_match=sorted_matches[0],
        tier=sorted_matches[0].tier,
        total_connections=len(sorted_matches),
    )


# =============================================================================
# MOVERS ALERT
# =============================================================================

def get_movers(limit: int = 50) -> list[Mover]:
    """Get contacts who recently moved companies."""
    conn = get_connection()
    cursor = conn.cursor()

    cursor.execute("""
        SELECT contact_name, colleague_owner, company, position,
               is_new_position, date_connected
        FROM network_graph
        WHERE is_new_company = 1
        ORDER BY date_imported DESC
        LIMIT ?
    """, (limit,))

    rows = cursor.fetchall()
    conn.close()

    movers = []
    for row in rows:
        movers.append(Mover(
            name=row[0], colleague=row[1], company=row[2] or 'Unknown',
            position=row[3] or 'Unknown', is_new_position=bool(row[4]),
            date_connected=row[5] or ''
        ))

    return movers


def get_movers_by_colleague(colleague: str = None) -> dict:
    """Get movers grouped by colleague."""
    conn = get_connection()
    cursor = conn.cursor()

    if colleague:
        cursor.execute("""
            SELECT contact_name, colleague_owner, company, position,
                   is_new_position, date_connected
            FROM network_graph
            WHERE is_new_company = 1 AND colleague_owner = ?
            ORDER BY date_imported DESC
        """, (colleague,))
    else:
        cursor.execute("""
            SELECT contact_name, colleague_owner, company, position,
                   is_new_position, date_connected
            FROM network_graph
            WHERE is_new_company = 1
            ORDER BY colleague_owner, date_imported DESC
        """)

    rows = cursor.fetchall()
    conn.close()

    by_colleague = {}
    for row in rows:
        mover = Mover(
            name=row[0], colleague=row[1], company=row[2] or 'Unknown',
            position=row[3] or 'Unknown', is_new_position=bool(row[4]),
            date_connected=row[5] or ''
        )
        if mover.colleague not in by_colleague:
            by_colleague[mover.colleague] = []
        by_colleague[mover.colleague].append(mover)

    return by_colleague


def generate_movers_report() -> str:
    """Generate a formatted movers alert report."""
    movers = get_movers()

    if not movers:
        return "No movers detected in your network."

    lines = []
    lines.append("=" * 60)
    lines.append("πŸš€ MOVERS ALERT - Network Movement Report")
    lines.append(f"   Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    lines.append("=" * 60)
    lines.append(f"\n   {len(movers)} contacts have moved to new companies!\n")
    lines.append("-" * 60)

    # Group by colleague
    by_colleague = {}
    for m in movers:
        if m.colleague not in by_colleague:
            by_colleague[m.colleague] = []
        by_colleague[m.colleague].append(m)

    for colleague, colleague_movers in by_colleague.items():
        lines.append(f"\nπŸ‘€ {colleague}'s Network ({len(colleague_movers)} movers):")
        lines.append("-" * 40)

        for m in colleague_movers:
            new_role = " πŸ†• NEW ROLE" if m.is_new_position else ""
            lines.append(f"   πŸš€ {m.name}")
            lines.append(f"      β†’ Now at: {m.company}")
            lines.append(f"      β†’ Role: {m.position}{new_role}")
            lines.append(f"      πŸ’‘ ACTION: Reach out to congratulate and reconnect!")
            lines.append("")

    lines.append("=" * 60)
    lines.append("End of Movers Report")

    return "\n".join(lines)


# =============================================================================
# STATISTICS
# =============================================================================

def get_network_stats() -> dict:
    """Get network statistics."""
    conn = get_connection()
    cursor = conn.cursor()

    stats = {}

    cursor.execute("SELECT COUNT(*) FROM network_graph")
    stats['total_connections'] = cursor.fetchone()[0]

    cursor.execute("SELECT COUNT(DISTINCT company_normalized) FROM network_graph WHERE company_normalized != ''")
    stats['unique_companies'] = cursor.fetchone()[0]

    cursor.execute("SELECT COUNT(*) FROM network_graph WHERE is_senior = 1")
    stats['senior_connections'] = cursor.fetchone()[0]

    cursor.execute("SELECT COUNT(*) FROM network_graph WHERE is_new_company = 1")
    stats['movers'] = cursor.fetchone()[0]

    cursor.execute("SELECT COUNT(*) FROM network_graph WHERE is_new_position = 1")
    stats['promoted'] = cursor.fetchone()[0]

    cursor.execute("""
        SELECT colleague_owner, COUNT(*) as count
        FROM network_graph
        GROUP BY colleague_owner
        ORDER BY count DESC
    """)
    stats['by_colleague'] = cursor.fetchall()

    cursor.execute("SELECT name, connections_count, movers_count, last_import FROM team_members ORDER BY connections_count DESC")
    stats['team_members'] = cursor.fetchall()

    conn.close()
    return stats


# =============================================================================
# BRIEFING INTEGRATION
# =============================================================================

def format_network_hit_for_briefing(hit: NetworkHit) -> str:
    """Format a NetworkHit for the daily briefing."""
    if not hit.has_connection:
        return ""

    lines = []
    bm = hit.best_match

    if hit.tier == ConnectionTier.TIER_1_EXACT_ROLE:
        mover_flag = " πŸš€ RECENTLY MOVED!" if bm.is_mover else ""
        lines.append(f"   🎯 NETWORK HIT: {bm.colleague} knows {bm.name} ({bm.position}) at {hit.company}!{mover_flag}")

    elif hit.tier == ConnectionTier.TIER_2_SENIOR:
        mover_flag = " πŸš€" if bm.is_mover else ""
        lines.append(f"   ⭐ SENIOR CONNECTION: {bm.colleague} knows {bm.name} ({bm.position}){mover_flag}")

    else:
        if hit.total_connections > 1:
            by_colleague = {}
            for m in hit.matches:
                if m.colleague not in by_colleague:
                    by_colleague[m.colleague] = []
                by_colleague[m.colleague].append(m)

            for colleague, conns in list(by_colleague.items())[:2]:
                if len(conns) > 1:
                    lines.append(f"   πŸ”— {colleague} knows {len(conns)} people at {hit.company}")
                else:
                    lines.append(f"   πŸ”— {colleague} knows {conns[0].name} ({conns[0].position})")
        else:
            mover_flag = " πŸš€" if bm.is_mover else ""
            lines.append(f"   πŸ”— {bm.colleague} knows {bm.name} ({bm.position}){mover_flag}")

    return "\n".join(lines)


def check_lead_connections(company: str, role: str = None) -> dict:
    """Check network connections for a lead."""
    hit = find_network_hit(company, role)

    return {
        'has_connection': hit.has_connection,
        'tier': hit.tier.value,
        'tier_name': hit.best_match.tier_label if hit.best_match else 'NO CONNECTION',
        'tier_emoji': hit.best_match.tier_emoji if hit.best_match else '❄️',
        'summary': hit.summary,
        'total_connections': hit.total_connections,
        'best_match': {
            'name': hit.best_match.name,
            'position': hit.best_match.position,
            'colleague': hit.best_match.colleague,
            'is_senior': hit.best_match.is_senior,
            'is_mover': hit.best_match.is_mover,
        } if hit.best_match else None,
        'all_matches': [
            {
                'name': m.name, 'position': m.position, 'colleague': m.colleague,
                'tier': m.tier_label, 'is_senior': m.is_senior, 'is_mover': m.is_mover,
            }
            for m in hit.matches[:10]
        ],
        'briefing_text': format_network_hit_for_briefing(hit),
    }


# =============================================================================
# CLI INTERFACE
# =============================================================================

def print_stats():
    """Print network statistics."""
    stats = get_network_stats()

    print(f"\n{'='*60}")
    print("πŸ“Š NETWORK INTELLIGENCE STATS")
    print(f"{'='*60}")
    print(f"\n   Total Connections: {stats['total_connections']}")
    print(f"   Unique Companies: {stats['unique_companies']}")
    print(f"   Senior Connections: {stats['senior_connections']}")
    print(f"   πŸš€ Movers: {stats['movers']}")
    print(f"   πŸ“ˆ Promoted: {stats['promoted']}")

    if stats['by_colleague']:
        print(f"\n   Connections by Team Member:")
        for colleague, count in stats['by_colleague']:
            print(f"      β€’ {colleague}: {count}")


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description='Network Loader - LinkedIn Connection Intelligence')
    parser.add_argument('--file', type=str, default=DEFAULT_CSV_FILE, help='CSV file to load')
    parser.add_argument('--clear', action='store_true', help='Clear existing data before loading')
    parser.add_argument('--match', type=str, help='Test matching against a company')
    parser.add_argument('--role', type=str, help='Target role to match (used with --match)')
    parser.add_argument('--movers', action='store_true', help='Show movers alert report')
    parser.add_argument('--stats', action='store_true', help='Show network statistics')

    args = parser.parse_args()

    init_network_tables()

    if args.stats:
        print_stats()

    elif args.movers:
        print(generate_movers_report())

    elif args.match:
        print(f"\nπŸ” Finding connections at: {args.match}")
        if args.role:
            print(f"   Target role: {args.role}")

        hit = find_network_hit(args.match, args.role)
        print(f"\n{hit.summary}")

        if hit.matches:
            print(f"\n   All Connections ({hit.total_connections}):")
            for m in hit.matches[:10]:
                senior_flag = " ⭐" if m.is_senior else ""
                mover_flag = " πŸš€" if m.is_mover else ""
                print(f"      {m.tier_emoji} {m.name} ({m.position}){senior_flag}{mover_flag}")
                print(f"         Via: {m.colleague} | Match: {m.match_score:.0f}%")

        if hit.has_connection:
            print(f"\nπŸ“‹ Briefing Format:")
            print(format_network_hit_for_briefing(hit))

    else:
        print(f"\nπŸ“₯ Loading: {args.file}")
        result = load_csv(args.file, clear_existing=args.clear)

        if result['success']:
            print(f"\nβœ… Import Complete!")
            print(f"   Rows processed: {result['total_rows']}")
            print(f"   Imported: {result['imported']}")
            print(f"   Skipped: {result['skipped']}")
            print(f"   πŸš€ Movers: {result['movers']}")
            print(f"   πŸ“ˆ Promoted: {result['promoted']}")
            print(f"   Team Members: {', '.join(result.get('colleagues', []))}")

            print_stats()
        else:
            print(f"\n❌ Import Failed: {result.get('error', 'Unknown')}")