File size: 26,963 Bytes
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
68697dc
 
 
 
 
74888a1
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
68697dc
 
 
 
74888a1
 
68697dc
 
74888a1
 
 
 
 
68697dc
 
74888a1
68697dc
 
74888a1
 
 
 
 
 
 
 
 
68697dc
 
 
 
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
74888a1
 
 
 
 
 
 
68697dc
 
74888a1
68697dc
 
74888a1
68697dc
 
 
74888a1
 
68697dc
 
74888a1
 
 
 
 
68697dc
 
74888a1
 
 
 
68697dc
 
74888a1
68697dc
 
74888a1
 
68697dc
 
74888a1
 
 
 
68697dc
 
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
74888a1
68697dc
 
 
 
 
74888a1
 
 
 
 
 
68697dc
 
 
74888a1
68697dc
 
74888a1
68697dc
 
 
74888a1
68697dc
 
 
 
74888a1
 
68697dc
74888a1
 
 
 
 
 
 
68697dc
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
74888a1
 
 
 
68697dc
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
74888a1
 
 
68697dc
 
 
74888a1
68697dc
 
 
 
 
74888a1
 
 
68697dc
74888a1
 
68697dc
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
74888a1
68697dc
 
 
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
74888a1
68697dc
 
 
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
74888a1
68697dc
 
 
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
68697dc
 
74888a1
68697dc
 
 
 
 
 
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
 
 
 
 
 
 
74888a1
 
 
 
68697dc
 
 
 
 
 
 
 
 
74888a1
68697dc
 
74888a1
68697dc
 
 
74888a1
 
 
 
 
 
 
 
 
 
68697dc
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
74888a1
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
 
68697dc
 
 
 
 
 
74888a1
68697dc
74888a1
68697dc
 
74888a1
68697dc
 
 
74888a1
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
74888a1
68697dc
 
 
 
 
 
 
 
74888a1
68697dc
 
 
 
 
 
74888a1
 
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
68697dc
 
 
 
 
 
 
 
 
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
"""Excel/CSV report generation for IP violation analysis results."""

import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.drawing.image import Image as ExcelImage
import os
from typing import List, Dict
from loguru import logger
from datetime import datetime


class CSVReportGenerator:
    """Generate Excel/CSV reports with multiple sheets."""

    def __init__(self, output_dir: str = "output/reports"):
        """
        Initialize report generator.

        Args:
            output_dir: Directory to save reports
        """
        self.output_dir = output_dir
        os.makedirs(output_dir, exist_ok=True)

    def generate_report(
        self,
        results: List[Dict],
        thumbnail_map: Dict[str, str],
        output_filename: str = None,
    ) -> str:
        """
        Generate client-friendly Excel report with 3 focused sheets.

        Args:
            results: List of analysis results
            thumbnail_map: Mapping of image_id to thumbnail path
            output_filename: Optional output filename

        Returns:
            Path to generated Excel file
        """
        if output_filename is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_filename = f"analysis_report_{timestamp}.xlsx"

        output_path = os.path.join(self.output_dir, output_filename)

        # Create 3 client-focused sheets
        with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
            # Sheet 1: Publishing Dashboard
            self._create_dashboard_sheet(results, thumbnail_map, writer)

            # Sheet 2: Detailed Analysis
            self._create_detailed_analysis_sheet(results, thumbnail_map, writer)

            # Sheet 3: Summary Report
            self._create_summary_report_sheet(results, writer)

        # Apply formatting (color coding, column widths)
        self._apply_formatting(output_path, thumbnail_map)

        logger.info(f"Excel report generated: {output_path}")
        return output_path

    def _create_dashboard_sheet(
        self, results: List[Dict], thumbnail_map: Dict[str, str], writer
    ) -> None:
        """Create Publishing Dashboard sheet - client-focused quick decision view."""
        rows = []

        for result in results:
            consensus = result.get("consensus", {})
            image_id = result.get("image_meta", {}).get("image_id", "unknown")

            # Format image ID nicely (Page 3 Image 1 instead of page_03_img_001)
            formatted_id = (
                image_id.replace("_", " ")
                .replace("page", "Page")
                .replace("img", "Image")
            )

            # Get thumbnail path (will show as local path in Excel)
            thumbnail_path = thumbnail_map.get(image_id, "[No image]")

            row = {
                "Image": thumbnail_path,  # Thumbnail file path
                "Image ID": formatted_id,
                "Status": consensus.get("status", "⚠️ NEEDS REVIEW"),
                "Risk Level": consensus.get("risk_level", "Unknown"),
                "Match Found": consensus.get("identified_ip", "None"),
                "Rights Holder": consensus.get("ip_owner", "N/A"),
                "Match Strength": f"{consensus.get('avg_similarity', 0):.0f}% match to original",
                "AI Agreement": consensus.get("ai_agreement_text", "Unknown"),
                "Action Required": consensus.get("action_required", "Review required"),
            }
            rows.append(row)

        df = pd.DataFrame(rows)

        # Sort by risk level (Critical > High > Moderate > Minimal)
        risk_order = {
            "Critical Risk": 0,
            "High Risk": 1,
            "Moderate Risk": 2,
            "Minimal Risk": 3,
            "Unknown": 4,
        }
        df["_sort"] = df["Risk Level"].map(risk_order)
        df = df.sort_values("_sort").drop("_sort", axis=1)

        df.to_excel(writer, sheet_name="Publishing Dashboard", index=False)

    def _create_detailed_analysis_sheet(
        self, results: List[Dict], thumbnail_map: Dict[str, str], writer
    ) -> None:
        """Create Detailed Analysis sheet - deep dive with redesign suggestions."""
        rows = []

        for result in results:
            consensus = result.get("consensus", {})
            image_id = result.get("image_meta", {}).get("image_id", "unknown")
            formatted_id = (
                image_id.replace("_", " ")
                .replace("page", "Page")
                .replace("img", "Image")
            )

            # Get thumbnail path
            thumbnail_path = thumbnail_map.get(image_id, "[No image]")

            # Format "What Matches" from matching_elements_detailed
            matching_elements = consensus.get("matching_elements", {})
            what_matches = []
            for category, details in matching_elements.items():
                if isinstance(details, dict):
                    desc = details.get("description", "")
                    if desc and desc != "No match":
                        what_matches.append(f"• {category.title()}: {desc}")

            what_matches_str = (
                "\n".join(what_matches)
                if what_matches
                else "No specific elements identified"
            )

            # Format "Suggested Changes"
            suggestions = consensus.get("redesign_suggestions", [])
            suggested_changes = (
                "\n".join([f"• {s}" for s in suggestions]) if suggestions else "N/A"
            )

            # Model details — dynamic across 1-3 models
            model_results = result.get("model_results", [])
            model_parts = [
                f"{r.get('provider', r.get('model', 'Model'))}: {r.get('similarity_percentage', 0):.0f}%"
                for r in model_results
                if "similarity_percentage" in r
            ]
            if model_parts:
                model_details = (
                    " | ".join(model_parts)
                    + f" | Avg: {consensus.get('avg_similarity', 0):.0f}%\nModel variance: {consensus.get('similarity_stddev', 0):.1f}%"
                )
            else:
                model_details = "No model data"

            row = {
                "Image": thumbnail_path,  # Thumbnail file path
                "Image ID": formatted_id,
                "Status": consensus.get("status", "⚠️"),
                "Risk Level": consensus.get("risk_level", "Unknown"),
                "Match Found": consensus.get("identified_ip", "None"),
                "Rights Holder": consensus.get("ip_owner", "N/A"),
                "Match Strength": f"{consensus.get('avg_similarity', 0):.0f}% match",
                "What Matches": what_matches_str,
                "Why It's Flagged": consensus.get(
                    "combined_description", "No description"
                ),  # FULL text
                "Suggested Changes": suggested_changes,
                "Model Details": model_details,
            }
            rows.append(row)

        df = pd.DataFrame(rows)
        df.to_excel(writer, sheet_name="Detailed Analysis", index=False)

    def _create_summary_report_sheet(self, results: List[Dict], writer) -> None:
        """Create Summary Report sheet - high-level overview for legal review."""
        # Count status categories
        status_counts = {}
        risk_counts = {
            "Minimal Risk": 0,
            "Moderate Risk": 0,
            "High Risk": 0,
            "Critical Risk": 0,
        }
        ip_owner_risks = {}

        for result in results:
            consensus = result.get("consensus", {})

            # Status
            status = consensus.get("status", "⚠️ NEEDS REVIEW")
            status_counts[status] = status_counts.get(status, 0) + 1

            # Risk
            risk = consensus.get("risk_level", "Unknown")
            if risk in risk_counts:
                risk_counts[risk] += 1

            # IP owners
            ip_owner = consensus.get("ip_owner", "Unknown")
            similarity = consensus.get("avg_similarity", 0)
            if ip_owner not in ip_owner_risks:
                ip_owner_risks[ip_owner] = {"count": 0, "max_risk": 0, "max_image": ""}
            ip_owner_risks[ip_owner]["count"] += 1
            if similarity > ip_owner_risks[ip_owner]["max_risk"]:
                ip_owner_risks[ip_owner]["max_risk"] = similarity
                ip_owner_risks[ip_owner]["max_image"] = result.get(
                    "image_meta", {}
                ).get("image_id", "unknown")

        # Section A: Key Metrics
        metrics_rows = [
            ["Total Images Analyzed", len(results)],
            ["Analysis Date", datetime.now().strftime("%Y-%m-%d")],
            ["Models Used", "GPT-5.2 + Gemini 3.1 Pro + Claude Opus 4.6"],
            ["", ""],
            ["PUBLISHING STATUS", ""],
            ["✅ Safe to Publish", status_counts.get("✅ SAFE TO PUBLISH", 0)],
            ["⚠️ Needs Review", status_counts.get("⚠️ NEEDS REVIEW", 0)],
            ["❌ Do Not Publish", status_counts.get("❌ DO NOT PUBLISH", 0)],
            ["", ""],
            ["RISK BREAKDOWN", ""],
            ["Minimal Risk (0-40%)", risk_counts["Minimal Risk"]],
            ["Moderate Risk (41-60%)", risk_counts["Moderate Risk"]],
            ["High Risk (61-80%)", risk_counts["High Risk"]],
            ["Critical Risk (81-100%)", risk_counts["Critical Risk"]],
        ]

        df_metrics = pd.DataFrame(metrics_rows, columns=["Metric", "Value"])
        df_metrics.to_excel(
            writer, sheet_name="Summary Report", index=False, startrow=0
        )

        # Section B: IP Owners (write below metrics)
        ip_rows = []
        for owner, data in sorted(
            ip_owner_risks.items(), key=lambda x: x[1]["count"], reverse=True
        ):
            ip_rows.append(
                {
                    "Rights Holder": owner,
                    "Images Flagged": data["count"],
                    "Highest Risk Image": f"{data['max_image']} ({data['max_risk']:.0f}%)",
                    "Action Needed": "Legal review + redesign"
                    if data["max_risk"] > 60
                    else "Review required",
                }
            )

        df_ip = pd.DataFrame(ip_rows)
        # Write below metrics section
        startrow = len(metrics_rows) + 3
        df_ip.to_excel(
            writer, sheet_name="Summary Report", index=False, startrow=startrow
        )

    # OLD METHODS KEPT FOR BACKWARD COMPATIBILITY (not used in new generate_report)
    def _create_all_results_sheet(
        self, results: List[Dict], thumbnail_map: Dict[str, str]
    ) -> pd.DataFrame:
        """Create sheet with all model results."""
        rows = []

        for result in results:
            image_meta = result.get("image_meta", {})
            image_id = image_meta.get("image_id", "unknown")
            thumbnail_path = thumbnail_map.get(image_id, "")

            model_results = result.get("model_results", [])
            consensus = result.get("consensus", {})

            # Add row for each model
            for model_result in model_results:
                if "error" not in model_result:
                    rows.append(
                        {
                            "Image ID": image_id,
                            "Thumbnail Path": thumbnail_path,
                            "Model": model_result.get("model", "unknown"),
                            "IP Violation": model_result.get("ip_violation", "UNKNOWN"),
                            "Similarity %": model_result.get(
                                "similarity_percentage", 0
                            ),
                            "Identified IP": model_result.get("identified_ip", "None"),
                            "IP Category": model_result.get("ip_category", "None"),
                            "Confidence": model_result.get("confidence", "UNKNOWN"),
                            "Reason": model_result.get("clash_description", "")[:200],
                            "Legal Risk": model_result.get(
                                "legal_risk_level", "UNKNOWN"
                            ),
                        }
                    )

            # Add consensus row
            rows.append(
                {
                    "Image ID": image_id,
                    "Thumbnail Path": thumbnail_path,
                    "Model": "**CONSENSUS**",
                    "IP Violation": consensus.get("ip_violation", "UNKNOWN"),
                    "Similarity %": consensus.get("avg_similarity", 0),
                    "Identified IP": consensus.get("identified_ip", "None"),
                    "IP Category": "-",
                    "Confidence": consensus.get("consensus_type", "UNKNOWN"),
                    "Reason": consensus.get("combined_description", "")[:200],
                    "Legal Risk": "HIGH"
                    if consensus.get("avg_similarity", 0) > 60
                    else "MEDIUM"
                    if consensus.get("avg_similarity", 0) > 40
                    else "LOW",
                }
            )

        return pd.DataFrame(rows)

    def _create_consensus_sheet(
        self, results: List[Dict], thumbnail_map: Dict[str, str]
    ) -> pd.DataFrame:
        """Create sheet with consensus summary."""
        rows = []

        for result in results:
            image_meta = result.get("image_meta", {})
            image_id = image_meta.get("image_id", "unknown")
            thumbnail_path = thumbnail_map.get(image_id, "")

            consensus = result.get("consensus", {})

            rows.append(
                {
                    "Image ID": image_id,
                    "Thumbnail Path": thumbnail_path,
                    "Consensus": consensus.get("ip_violation", "UNKNOWN"),
                    "Type": consensus.get("consensus_type", "UNKNOWN"),
                    "Similarity %": consensus.get("avg_similarity", 0),
                    "Std Dev": consensus.get("similarity_stddev", 0),
                    "Identified IP": consensus.get("identified_ip", "None"),
                    "Model Agreement": consensus.get("model_agreement", 0),
                    "Needs Review": consensus.get("needs_review", False),
                    "Description": consensus.get("combined_description", "")[:300],
                }
            )

        return pd.DataFrame(rows)

    def _create_high_risk_sheet(
        self, results: List[Dict], thumbnail_map: Dict[str, str]
    ) -> pd.DataFrame:
        """Create sheet with high-risk images (>60% similarity)."""
        rows = []

        for result in results:
            consensus = result.get("consensus", {})
            if consensus.get("avg_similarity", 0) > 60:
                image_meta = result.get("image_meta", {})
                image_id = image_meta.get("image_id", "unknown")
                thumbnail_path = thumbnail_map.get(image_id, "")

                rows.append(
                    {
                        "Image ID": image_id,
                        "Thumbnail Path": thumbnail_path,
                        "Similarity %": consensus.get("avg_similarity", 0),
                        "Identified IP": consensus.get("identified_ip", "None"),
                        "Consensus": consensus.get("ip_violation", "UNKNOWN"),
                        "Type": consensus.get("consensus_type", "UNKNOWN"),
                        "Description": consensus.get("combined_description", "")[:300],
                    }
                )

        return pd.DataFrame(rows)

    def _create_split_decisions_sheet(
        self, results: List[Dict], thumbnail_map: Dict[str, str]
    ) -> pd.DataFrame:
        """Create sheet with split decisions (models disagree)."""
        rows = []

        for result in results:
            consensus = result.get("consensus", {})
            if consensus.get("consensus_type") == "SPLIT_DECISION":
                image_meta = result.get("image_meta", {})
                image_id = image_meta.get("image_id", "unknown")
                thumbnail_path = thumbnail_map.get(image_id, "")

                rows.append(
                    {
                        "Image ID": image_id,
                        "Thumbnail Path": thumbnail_path,
                        "Similarity %": consensus.get("avg_similarity", 0),
                        "Std Dev": consensus.get("similarity_stddev", 0),
                        "Identified IP": consensus.get("identified_ip", "None"),
                        "Model Agreement": consensus.get("model_agreement", 0),
                        "Description": consensus.get("combined_description", "")[:300],
                    }
                )

        return pd.DataFrame(rows)

    def _create_statistics_sheet(self, results: List[Dict]) -> pd.DataFrame:
        """Create sheet with summary statistics."""
        total_images = len(results)

        # Count consensus types
        consensus_types = {}
        high_risk_count = 0
        medium_risk_count = 0

        for result in results:
            consensus = result.get("consensus", {})
            consensus_type = consensus.get("consensus_type", "UNKNOWN")
            consensus_types[consensus_type] = consensus_types.get(consensus_type, 0) + 1

            sim = consensus.get("avg_similarity", 0)
            if sim > 60:
                high_risk_count += 1
            elif sim >= 40:
                medium_risk_count += 1

        low_risk_count = total_images - high_risk_count - medium_risk_count

        rows = [
            {"Metric": "Total Images Analyzed", "Value": total_images},
            {"Metric": "", "Value": ""},
            {"Metric": "CONSENSUS BREAKDOWN", "Value": ""},
            {
                "Metric": "Both Agree - Violation",
                "Value": consensus_types.get("BOTH_AGREE_VIOLATION", 0),
            },
            {
                "Metric": "Both Agree - Safe",
                "Value": consensus_types.get("BOTH_AGREE_SAFE", 0),
            },
            {
                "Metric": "Split Decisions",
                "Value": consensus_types.get("SPLIT_DECISION", 0),
            },
            {
                "Metric": "Single Model Only",
                "Value": consensus_types.get("SINGLE_MODEL_ONLY", 0),
            },
            {"Metric": "", "Value": ""},
            {"Metric": "RISK BREAKDOWN", "Value": ""},
            {"Metric": "High Risk (>60%)", "Value": high_risk_count},
            {"Metric": "Medium Risk (40-60%)", "Value": medium_risk_count},
            {"Metric": "Low Risk (<40%)", "Value": low_risk_count},
        ]

        return pd.DataFrame(rows)

    def _apply_formatting(self, excel_path: str, thumbnail_map: Dict[str, str]):
        """Apply color coding and formatting to new 3-sheet layout."""
        try:
            wb = load_workbook(excel_path)

            # Common header formatting
            header_fill = PatternFill(
                start_color="4472C4", end_color="4472C4", fill_type="solid"
            )
            header_font = Font(bold=True, color="FFFFFF")

            # Format each sheet
            for sheet_name in wb.sheetnames:
                ws = wb[sheet_name]

                # Apply header formatting
                for cell in ws[1]:
                    cell.fill = header_fill
                    cell.font = header_font
                    cell.alignment = Alignment(horizontal="center", vertical="center")

                # Sheet-specific formatting
                if sheet_name == "Publishing Dashboard":
                    # Apply color coding by Status column
                    self._apply_dashboard_colors(ws)
                    # Set column widths
                    ws.column_dimensions["A"].width = 20  # Image ID
                    ws.column_dimensions["B"].width = 25  # Status
                    ws.column_dimensions["C"].width = 20  # Risk Level
                    ws.column_dimensions["D"].width = 20  # Match Found
                    ws.column_dimensions["E"].width = 18  # Rights Holder
                    ws.column_dimensions["F"].width = 22  # Match Strength
                    ws.column_dimensions["G"].width = 35  # AI Agreement
                    ws.column_dimensions["H"].width = 30  # Action Required

                elif sheet_name == "Detailed Analysis":
                    # Set column widths for detailed view
                    ws.column_dimensions["A"].width = 20  # Image ID
                    ws.column_dimensions["B"].width = 20  # Status
                    ws.column_dimensions["C"].width = 18  # Risk Level
                    ws.column_dimensions["D"].width = 20  # Match Found
                    ws.column_dimensions["E"].width = 18  # Rights Holder
                    ws.column_dimensions["F"].width = 18  # Match Strength
                    ws.column_dimensions["G"].width = 50  # What Matches
                    ws.column_dimensions[
                        "H"
                    ].width = 80  # Why It's Flagged (wide for full text)
                    ws.column_dimensions["I"].width = 50  # Suggested Changes
                    ws.column_dimensions["J"].width = 30  # Model Details

                elif sheet_name == "Summary Report":
                    # Set column widths for summary
                    ws.column_dimensions["A"].width = 35  # Metric
                    ws.column_dimensions["B"].width = 15  # Value

            wb.save(excel_path)
            logger.info("Applied formatting with color coding")

        except Exception as e:
            logger.error(f"Failed to apply formatting: {e}")

    def _apply_dashboard_colors(self, ws):
        """Apply color coding to Publishing Dashboard based on Status column."""
        # Find Status column (usually column B, index 2)
        status_col = 2

        for row in range(2, ws.max_row + 1):
            status_cell = ws.cell(row, status_col)
            status = str(status_cell.value)

            # Determine colors based on status
            if "✅" in status:
                fill = PatternFill(
                    start_color="C6EFCE", end_color="C6EFCE", fill_type="solid"
                )
                font = Font(color="006100")
            elif "❌" in status:
                fill = PatternFill(
                    start_color="FFC7CE", end_color="FFC7CE", fill_type="solid"
                )
                font = Font(color="9C0006")
            elif "⚠️" in status:
                fill = PatternFill(
                    start_color="FFEB9C", end_color="FFEB9C", fill_type="solid"
                )
                font = Font(color="9C5700")
            else:
                continue

            # Apply to entire row
            for col in range(1, ws.max_column + 1):
                cell = ws.cell(row, col)
                cell.fill = fill
                cell.font = font

    # OLD METHOD - kept for backward compatibility but not used in new reports
    def _apply_formatting_old(self, excel_path: str, thumbnail_map: Dict[str, str]):
        """OLD: Apply formatting to Excel workbook and embed thumbnails."""
        try:
            wb = load_workbook(excel_path)

            # Format each sheet
            for sheet_name in wb.sheetnames:
                ws = wb[sheet_name]

                # Header formatting
                header_fill = PatternFill(
                    start_color="4472C4", end_color="4472C4", fill_type="solid"
                )
                header_font = Font(bold=True, color="FFFFFF")

                # Find the thumbnail column index
                thumbnail_col_idx = None
                for idx, cell in enumerate(ws[1], start=1):
                    cell.fill = header_fill
                    cell.font = header_font
                    cell.alignment = Alignment(horizontal="center", vertical="center")

                    if cell.value == "Thumbnail Path":
                        thumbnail_col_idx = idx
                        # Rename header to "Thumbnail"
                        cell.value = "Thumbnail"

                # Embed thumbnails if column exists
                if thumbnail_col_idx:
                    thumbnail_col_letter = ws.cell(
                        row=1, column=thumbnail_col_idx
                    ).column_letter

                    # Set thumbnail column width
                    ws.column_dimensions[thumbnail_col_letter].width = 15

                    # Insert thumbnails
                    for row_idx in range(2, ws.max_row + 1):
                        cell = ws.cell(row=row_idx, column=thumbnail_col_idx)
                        thumbnail_path = cell.value

                        if thumbnail_path and os.path.exists(thumbnail_path):
                            try:
                                # Clear the cell text
                                cell.value = ""

                                # Insert image
                                img = ExcelImage(thumbnail_path)
                                # Resize to fit in cell (100 pixels height)
                                img.height = 100
                                img.width = 100

                                # Position image in cell
                                img.anchor = f"{thumbnail_col_letter}{row_idx}"
                                ws.add_image(img)

                                # Set row height to fit image (in points, 1 point = 1.33 pixels approx)
                                ws.row_dimensions[row_idx].height = 75

                            except Exception as e:
                                logger.warning(
                                    f"Failed to embed thumbnail {thumbnail_path}: {e}"
                                )
                                cell.value = "Image error"

                # Auto-adjust other column widths
                for column in ws.columns:
                    column_letter = column[0].column_letter
                    # Skip thumbnail column as we already set it
                    if thumbnail_col_idx and column_letter == thumbnail_col_letter:
                        continue

                    max_length = 0
                    for cell in column:
                        try:
                            if len(str(cell.value)) > max_length:
                                max_length = len(str(cell.value))
                        except Exception:
                            pass
                    adjusted_width = min(max_length + 2, 50)
                    ws.column_dimensions[column_letter].width = adjusted_width

            wb.save(excel_path)
            logger.info("Excel formatting and thumbnails applied")

        except Exception as e:
            logger.warning(f"Failed to apply Excel formatting: {e}")