"""
Coverage Reporter - Generates comprehensive coverage reports for API, Database, Model-Schema, and Migration
"""
import html as html_escape
import json
from pathlib import Path
from typing import Dict, Optional, List
from datetime import datetime


class CoverageReporter:
    """Generate comprehensive coverage reports for the test suite"""
    
    def __init__(self, project_dir: str, version: str = "unknown"):
        self.project_dir = Path(project_dir)
        self.version = version
        self.reports_dir = self.project_dir / "tests" / "reports"
        self.reports_dir.mkdir(exist_ok=True)
    
    def generate_comprehensive_report(
        self,
        api_coverage: Optional[Dict] = None,
        db_coverage: Optional[Dict] = None,
        model_schema_coverage: Optional[Dict] = None,
        migration_consistency: Optional[Dict] = None,
        schema_payload_issues: Optional[list] = None,
        database_consistency_issues: Optional[list] = None,
        permissions_summary: Optional[Dict] = None
    ) -> str:
        """Generate comprehensive coverage report in HTML and Markdown formats"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

        # Generate HTML report
        html_report = self._generate_html_report(
            api_coverage, db_coverage, model_schema_coverage, migration_consistency, schema_payload_issues, database_consistency_issues, permissions_summary, timestamp
        )
        
        # Generate Markdown report
        md_report = self._generate_markdown_report(
            api_coverage, db_coverage, model_schema_coverage, migration_consistency,
            schema_payload_issues, database_consistency_issues, permissions_summary, timestamp
        )
        
        # Save reports
        html_file = self.reports_dir / f"coverage-report-{timestamp}.html"
        md_file = self.reports_dir / f"coverage-report-{timestamp}.md"
        
        with open(html_file, 'w', encoding='utf-8') as f:
            f.write(html_report)
        
        with open(md_file, 'w', encoding='utf-8') as f:
            f.write(md_report)
        
        # Also save latest reports
        latest_html = self.reports_dir / "coverage-report-latest.html"
        latest_md = self.reports_dir / "coverage-report-latest.md"
        
        with open(latest_html, 'w', encoding='utf-8') as f:
            f.write(html_report)
        
        with open(latest_md, 'w', encoding='utf-8') as f:
            f.write(md_report)
        
        return str(html_file)
    
    def _generate_html_report(
        self,
        api_coverage: Optional[Dict] = None,
        db_coverage: Optional[Dict] = None,
        model_schema_coverage: Optional[Dict] = None,
        migration_consistency: Optional[Dict] = None,
        schema_payload_issues: Optional[list] = None,
        database_consistency_issues: Optional[list] = None,
        permissions_summary: Optional[Dict] = None,
        timestamp: str = ""
    ) -> str:
        """Generate HTML coverage report"""
        html = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StreamA2026 Coverage Report</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
        }}
        .header h1 {{
            margin: 0;
            font-size: 2em;
        }}
        .header .timestamp {{
            opacity: 0.8;
            margin-top: 10px;
        }}
        .section {{
            background: white;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }}
        .section h2 {{
            margin-top: 0;
            color: #333;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }}
        .metric {{
            display: inline-block;
            margin: 10px 20px 10px 0;
            padding: 15px 20px;
            background: #f8f9fa;
            border-radius: 8px;
            min-width: 150px;
        }}
        .metric .label {{
            font-size: 0.85em;
            color: #666;
            text-transform: uppercase;
        }}
        .metric .value {{
            font-size: 1.8em;
            font-weight: bold;
            color: #333;
        }}
        .metric.success .value {{
            color: #28a745;
        }}
        .metric.warning .value {{
            color: #ffc107;
        }}
        .metric.error .value {{
            color: #dc3545;
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }}
        th, td {{
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }}
        th {{
            background-color: #f8f9fa;
            font-weight: 600;
        }}
        tr:hover {{
            background-color: #f5f5f5;
        }}
        .badge {{
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.85em;
            font-weight: 600;
        }}
        .badge-success {{
            background-color: #d4edda;
            color: #155724;
        }}
        .badge-warning {{
            background-color: #fff3cd;
            color: #856404;
        }}
        .badge-danger {{
            background-color: #f8d7da;
            color: #721c24;
        }}
        .endpoint-list {{
            max-height: 300px;
            overflow-y: auto;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
        }}
        .endpoint-item {{
            padding: 8px;
            border-bottom: 1px solid #ddd;
        }}
        .endpoint-item:last-child {{
            border-bottom: none;
        }}
        .method {{
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 0.8em;
            font-weight: bold;
            margin-right: 8px;
        }}
        .method-GET {{ background: #61affe; color: white; }}
        .method-POST {{ background: #49cc90; color: white; }}
        .method-PUT {{ background: #fca130; color: white; }}
        .method-DELETE {{ background: #f93e3e; color: white; }}
        .method-PATCH {{ background: #50e3c2; color: white; }}
    </style>
</head>
<body>
    <div class="header">
        <h1>📊 StreamA2026 Coverage Report</h1>
        <div class="timestamp">Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</div>
    </div>
"""
        
        # API Endpoint Coverage Section
        if api_coverage:
            html += self._generate_api_coverage_html(api_coverage)
        
        # Database Schema Coverage Section
        if db_coverage:
            html += self._generate_db_coverage_html(db_coverage)
        
        # Model-Schema Coverage Section
        if model_schema_coverage:
            html += self._generate_model_schema_coverage_html(model_schema_coverage)
        
        # Migration Consistency Section
        if migration_consistency:
            html += self._generate_migration_consistency_html(migration_consistency)

        # Schema-Payload Validation Section
        if schema_payload_issues:
            html += self._generate_schema_payload_validation_html(schema_payload_issues)

            html += self._generate_database_consistency_html(database_consistency_issues)

        # Permissions Summary Section
        if permissions_summary and "error" not in permissions_summary:
            html += self._generate_permissions_html(permissions_summary)

        html += """
</body>
</html>
"""
        return html
    
    def _generate_api_coverage_html(self, coverage: Dict) -> str:
        """Generate API coverage section HTML"""
        html = """
    <div class="section">
        <h2>🔌 API Endpoint Coverage</h2>
        <div class="metric">
            <div class="label">Total Endpoints</div>
            <div class="value">{}</div>
        </div>
        <div class="metric {}">
            <div class="label">Covered</div>
            <div class="value">{} ({})</div>
        </div>
        <div class="metric {}">
            <div class="label">Unused</div>
            <div class="value">{} ({})</div>
        </div>
        <div class="metric {}">
            <div class="label">Intentionally Unused</div>
            <div class="value">{} ({})</div>
        </div>
        <div class="metric {}">
            <div class="label">New</div>
            <div class="value">{}</div>
        </div>
""".format(
            coverage['total_backend_endpoints'],
            'success' if coverage['covered_percentage'] >= 90 else 'warning' if coverage['covered_percentage'] >= 70 else 'error',
            coverage['covered_count'],
            f"{coverage['covered_percentage']}%",
            'warning' if coverage['unused_percentage'] <= 10 else 'error',
            coverage['unused_count'],
            f"{coverage['unused_percentage']}%",
            'info',
            coverage.get('intentionally_unused_count', 0),
            f"{coverage.get('intentionally_unused_percentage', 0)}%",
            'info',
            coverage['new_endpoints_count']
        )
        
        if coverage.get('new_endpoints_count', 0) > 0 and coverage.get('new_endpoints'):
            html += """
        <h3>🆕 New Endpoints</h3>
        <div class="endpoint-list">
"""
            for endpoint in coverage['new_endpoints']:
                method = html_escape.escape(str(endpoint['method']))
                path = html_escape.escape(str(endpoint['path']))
                html += f"""
            <div class="endpoint-item">
                <span class="method method-{method}">{method}</span>
                <code>{path}</code>
                <span class="badge badge-success">NEW</span>
            </div>
"""
            html += """
        </div>
"""
        
        if coverage['unused_endpoints']:
            html += """
        <h3>⚠️ Unused Endpoints (may be intentional)</h3>
        <div class="endpoint-list">
"""
            for endpoint in coverage['unused_endpoints']:
                method = html_escape.escape(str(endpoint['method']))
                path = html_escape.escape(str(endpoint['path']))
                html += f"""
            <div class="endpoint-item">
                <span class="method method-{method}">{method}</span>
                <code>{path}</code>
                <span class="badge badge-warning">UNUSED</span>
            </div>
"""
            html += """
        </div>
"""

        # Intentionally Unused Endpoints Section
        if coverage.get('intentionally_unused_endpoints'):
            html += """
        <h3>🔧 Intentionally Unused (Internal Features)</h3>
        <div class="endpoint-list">
"""
            for endpoint in coverage['intentionally_unused_endpoints']:
                html += f"""
            <div class="endpoint-item">
                <span class="method method-{endpoint['method']}">{endpoint['method']}</span>
                <code>{endpoint['path']}</code>
                <span class="badge badge-info">INTERNAL</span>
            </div>
"""
            html += """
        </div>
"""

        html += """
    </div>
"""
        return html
    
    def _generate_db_coverage_html(self, coverage: Dict) -> str:
        """Generate database coverage section HTML"""
        html = """
    <div class="section">
        <h2>🗄️ Database Schema Coverage</h2>
        <div class="metric">
            <div class="label">Total Tables</div>
            <div class="value">{}</div>
        </div>
        <div class="metric success">
            <div class="label">Tables in DB</div>
            <div class="value">{}</div>
        </div>
""".format(
            coverage.get('total_tables', 'N/A'),
            coverage.get('tables_in_db', 'N/A')
        )
        
        if coverage.get('missing_tables'):
            html += """
        <h3>❌ Missing Tables</h3>
        <table>
            <tr><th>Table Name</th><th>Status</th></tr>
"""
            for table in coverage['missing_tables']:
                html += f"""
            <tr><td><code>{table}</code></td><td><span class="badge badge-danger">MISSING</span></td></tr>
"""
            html += """
        </table>
"""
        
        html += """
    </div>
"""
        return html
    
    def _generate_model_schema_coverage_html(self, coverage: Dict) -> str:
        """Generate model-schema coverage section HTML"""
        html = """
    <div class="section">
        <h2>📋 Model-Schema Coverage</h2>
        <div class="metric">
            <div class="label">Total Models</div>
            <div class="value">{}</div>
        </div>
        <div class="metric">
            <div class="label">Total Fields</div>
            <div class="value">{}</div>
        </div>
        <div class="metric {}">
            <div class="label">Coverage</div>
            <div class="value">{} ({})</div>
        </div>
""".format(
            coverage['total_models'],
            coverage['total_model_fields'],
            'success' if coverage['coverage_percentage'] >= 90 else 'warning' if coverage['coverage_percentage'] >= 70 else 'error',
            coverage['covered_fields'],
            f"{coverage['coverage_percentage']}%"
        )
        
        if coverage['missing_from_schemas']:
            html += """
        <h3>❌ Fields Missing from Schemas</h3>
        <table>
            <tr><th>Model</th><th>Field</th><th>Type</th></tr>
"""
            for model_name, fields in coverage['missing_from_schemas'].items():
                for field in fields:
                    html += f"""
            <tr><td>{model_name}</td><td><code>{field['name']}</code></td><td>{field['type']}</td></tr>
"""
            html += """
        </table>
"""
        
        html += """
    </div>
"""
        return html
    
    def _generate_migration_consistency_html(self, coverage: Dict) -> str:
        """Generate migration consistency section HTML"""
        status_class = 'success' if coverage['is_up_to_date'] else 'warning' if coverage['needs_upgrade'] else 'error'
        
        html = """
    <div class="section">
        <h2>🔄 Migration Consistency</h2>
        <div class="metric {}">
            <div class="label">Status</div>
            <div class="value">{}</div>
        </div>
        <div class="metric">
            <div class="label">Current Version</div>
            <div class="value">{}</div>
        </div>
        <div class="metric">
            <div class="label">Latest Migration</div>
            <div class="value">{}</div>
        </div>
        <div class="metric">
            <div class="label">Total Migrations</div>
            <div class="value">{}</div>
        </div>
""".format(
            status_class,
            'UP TO DATE' if coverage['is_up_to_date'] else 'NEEDS UPGRADE' if coverage['needs_upgrade'] else 'DRIFT DETECTED',
            coverage.get('current_version', 'N/A'),
            coverage.get('latest_revision', 'N/A'),
            coverage['total_migrations']
        )
        
        if coverage['model_changes']['needs_migration']:
            html += """
        <h3>⚠️ Model Changes Detected</h3>
        <p>{}</p>
""".format(coverage['model_changes']['reason'])
            if 'modified_models' in coverage['model_changes']:
                html += """
        <p>Modified models: {}</p>
""".format(', '.join(coverage['model_changes']['modified_models']))

        html += """
    </div>
"""
        return html

    def _generate_schema_payload_validation_html(self, issues: list) -> str:
        """Generate schema-payload validation section HTML"""
        if not issues:
            return """
    <div class="section">
        <h2>✅ Schema-Payload Validation</h2>
        <p>All TypeScript interfaces match backend Pydantic schemas.</p>
    </div>
"""

        html = """
    <div class="section">
        <h2>⚠️ Schema-Payload Validation</h2>
        <div class="metric error">
            <div class="label">Issues Found</div>
            <div class="value">{}</div>
        </div>
""".format(len(issues))

        for issue in issues:
            if issue.issue_type == "missing_interface":
                html += """
        <h3>❌ Missing TypeScript Interface</h3>
        <div class="issue-item">
            <p><strong>Endpoint:</strong> {} {}</p>
            <p><strong>Expected:</strong> {}</p>
            <p><strong>Actual:</strong> {}</p>
        </div>
""".format(issue.method, issue.endpoint, issue.expected, issue.actual)
            elif issue.issue_type == "extra_field":
                html += """
        <h3>⚠️ Extra Field in Interface</h3>
        <div class="issue-item">
            <p><strong>Field:</strong> <code>{}</code></p>
            <p><strong>Expected:</strong> {}</p>
            <p><strong>Actual:</strong> {}</p>
        </div>
""".format(issue.field_name, issue.expected, issue.actual)
            elif issue.issue_type == "missing_required_field":
                html += """
        <h3>❌ Missing Required Field in Interface</h3>
        <div class="issue-item">
            <p><strong>Field:</strong> <code>{}</code></p>
            <p><strong>Expected Type:</strong> {}</p>
            <p><strong>Actual:</strong> {}</p>
        </div>
""".format(issue.field_name, issue.expected, issue.actual)
            elif issue.issue_type == "orphan_interface":
                html += """
        <h3>⚠️ Orphan TypeScript Interface</h3>
        <div class="issue-item">
            <p><strong>Expected:</strong> {}</p>
            <p><strong>Actual:</strong> {}</p>
        </div>
""".format(issue.expected, issue.actual)

        html += """
    </div>
"""
        return html

    def _generate_database_consistency_html(self, issues: list) -> str:
        """Generate HTML for database consistency issues"""
        if not issues:
            return """
    <div class="section">
        <h2>🗄️ Database Consistency</h2>
        <p>✓ No database consistency issues found</p>
    </div>
"""

        # Group by issue type
        issues_by_type = {}
        for issue in issues:
            if issue.issue_type not in issues_by_type:
                issues_by_type[issue.issue_type] = []
            issues_by_type[issue.issue_type].append(issue)

        html = """
    <div class="section">
        <h2>🗄️ Database Consistency</h2>
        <p><strong>Total Issues:</strong> {}</p>
""".format(len(issues))

        for issue_type, type_issues in issues_by_type.items():
            html += f"""
        <h3>{issue_type.replace('_', ' ').title()}: {len(type_issues)}</h3>
"""
            for issue in type_issues:
                html += """
        <div class="issue-item">
            <p><strong>Model:</strong> {}</p>
            <p><strong>Schema:</strong> {}</p>
            <p><strong>Field:</strong> <code>{}</code></p>
            <p><strong>Model Type:</strong> {}</p>
            <p><strong>Schema Type:</strong> {}</p>
        </div>
""".format(issue.model_name, issue.schema_name, issue.field_name, issue.model_type, issue.schema_type)

        html += """
    </div>
"""
        return html

    def _generate_permissions_html(self, permissions_summary: Dict) -> str:
        """Generate permissions summary section HTML"""
        html = """
    <div class="section">
        <h2>🔐 Permissions Summary</h2>
        <div class="metric">
            <div class="label">Total Endpoints</div>
            <div class="value">{}</div>
        </div>
""".format(permissions_summary.get('total_endpoints', 0))
        
        # Unregistered endpoints
        unregistered = permissions_summary.get('unregistered', [])
        if unregistered:
            html += f"""
        <div class="metric">
            <div class="label">Unregistered</div>
            <div class="value">{len(unregistered)}</div>
        </div>
"""
            html += """
        <h3>🌐 Unregistered (No Auth Required)</h3>
        <div class="endpoint-list">
"""
            for item in unregistered:
                method = html_escape.escape(str(item['method']))
                endpoint = html_escape.escape(str(item['endpoint']))
                html += f"""
            <div class="endpoint-item">
                <span class="method method-{method}">{method}</span>
                <code>{endpoint}</code>
            </div>
"""
            html += """
        </div>
"""
        
        # Role-specific endpoints
        roles = permissions_summary.get('roles', {})
        for role_name in sorted(roles.keys()):
            endpoints = roles[role_name]
            html += f"""
        <h3>👤 {role_name.title()}</h3>
        <div class="metric">
            <div class="label">Endpoints</div>
            <div class="value">{len(endpoints)}</div>
        </div>
        <div class="endpoint-list">
"""
            for item in endpoints:
                method = html_escape.escape(str(item['method']))
                endpoint = html_escape.escape(str(item['endpoint']))
                roles_str = ', '.join(item['roles'])
                html += f"""
            <div class="endpoint-item">
                <span class="method method-{method}">{method}</span>
                <code>{endpoint}</code>
                <span class="badge badge-info">{roles_str}</span>
            </div>
"""
            html += """
        </div>
"""
        
        html += """
    </div>
"""
        return html

    def _generate_markdown_report(
        self,
        api_coverage: Optional[Dict],
        db_coverage: Optional[Dict],
        model_schema_coverage: Optional[Dict],
        migration_consistency: Optional[Dict],
        schema_payload_issues: Optional[List],
        database_consistency_issues: Optional[List],
        permissions_summary: Optional[Dict],
        timestamp: str
    ) -> str:
        """Generate Markdown coverage report"""
        md = f"""# StreamA2026 Coverage Report

**Generated:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}

---

"""
        
        # API Endpoint Coverage Section
        if api_coverage:
            md += f"""## 🔌 API Endpoint Coverage

| Metric | Value |
|--------|-------|
| Total Endpoints | {api_coverage['total_backend_endpoints']} |
| Covered | {api_coverage['covered_count']} ({api_coverage['covered_percentage']}%) |
| Unused | {api_coverage['unused_count']} ({api_coverage['unused_percentage']}%) |
"""
            if api_coverage.get('intentionally_unused_count', 0) > 0:
                md += f"| Intentionally Unused | {api_coverage['intentionally_unused_count']} ({api_coverage.get('intentionally_unused_percentage', 0)}%) |\n"
            md += f"| New | {api_coverage['new_endpoints_count']} |\n\n"

            if api_coverage['new_endpoints']:
                md += "### 🆕 New Endpoints\n\n"
                for endpoint in api_coverage['new_endpoints']:
                    md += f"- **{endpoint['method']}** `{endpoint['path']}` - NEW\n"
                md += "\n"

            if api_coverage['unused_endpoints']:
                md += "### ⚠️ Unused Endpoints (may be intentional)\n\n"
                for endpoint in api_coverage['unused_endpoints']:
                    md += f"- **{endpoint['method']}** `{endpoint['path']}`\n"
                md += "\n"

            if api_coverage.get('intentionally_unused_endpoints'):
                md += "### 🔧 Intentionally Unused (Internal Features)\n\n"
                for endpoint in api_coverage['intentionally_unused_endpoints']:
                    md += f"- **{endpoint['method']}** `{endpoint['path']}`\n"
                md += "\n"
        
        # Database Schema Coverage Section
        if db_coverage:
            md += f"""## 🗄️ Database Schema Coverage

| Metric | Value |
|--------|-------|
| Total Tables | {db_coverage.get('total_tables', 'N/A')} |
| Tables in DB | {db_coverage.get('tables_in_db', 'N/A')} |

"""
            if db_coverage.get('missing_tables'):
                md += "### ❌ Missing Tables\n\n"
                for table in db_coverage['missing_tables']:
                    md += f"- `{table}` - MISSING\n"
                md += "\n"
        
        # Model-Schema Coverage Section
        if model_schema_coverage:
            md += f"""## 📋 Model-Schema Coverage

| Metric | Value |
|--------|-------|
| Total Models | {model_schema_coverage['total_models']} |
| Total Fields | {model_schema_coverage['total_model_fields']} |
| Coverage | {model_schema_coverage['covered_fields']} ({model_schema_coverage['coverage_percentage']}%) |

"""
            if model_schema_coverage['missing_from_schemas']:
                md += "### ❌ Fields Missing from Schemas\n\n"
                md += "| Model | Field | Type |\n|-------|-------|------|\n"
                for model_name, fields in model_schema_coverage['missing_from_schemas'].items():
                    for field in fields:
                        md += f"| {model_name} | `{field['name']}` | {field['type']} |\n"
                md += "\n"
        
        # Migration Consistency Section
        if migration_consistency:
            status = '✅ UP TO DATE' if migration_consistency['is_up_to_date'] else '⚠️ NEEDS UPGRADE' if migration_consistency['needs_upgrade'] else '❌ DRIFT DETECTED'
            md += f"""## 🔄 Migration Consistency

| Metric | Value |
|--------|-------|
| Status | {status} |
| Current Version | {migration_consistency.get('current_version', 'N/A')} |
| Latest Migration | {migration_consistency.get('latest_revision', 'N/A')} |
| Total Migrations | {migration_consistency['total_migrations']} |

"""
            if migration_consistency['model_changes']['needs_migration']:
                md += f"### ⚠️ Model Changes Detected\n\n"
                md += f"{migration_consistency['model_changes']['reason']}\n\n"
                if 'modified_models' in migration_consistency['model_changes']:
                    md += f"Modified models: {', '.join(migration_consistency['model_changes']['modified_models'])}\n\n"

        # Schema-Payload Validation Section
        if schema_payload_issues:
            md += f"""## ⚠️ Schema-Payload Validation

**Issues Found:** {len(schema_payload_issues)}

"""
            for issue in schema_payload_issues:
                severity = "❌" if issue.issue_type in ["missing_required_field", "missing_interface", "orphan_interface", "missing_in_backend"] else "⚠️"
                md += f"{severity} {issue.issue_type}\n"
                md += f"Field: {issue.field_name}\n"
                md += f"Expected: {issue.expected}\n"
                md += f"Actual: {issue.actual}\n\n"

        # Database Consistency Section
        if database_consistency_issues:
            md += f"""## 🗄️ Database Consistency

**Total Issues:** {len(database_consistency_issues)}

"""
            for issue in database_consistency_issues:
                md += f"- {issue.issue_type}\n"
                md += f"  Model: {issue.model_name}\n"
                md += f"  Schema: {issue.schema_name}\n"
                md += f"  Field: {issue.field_name}\n\n"

        # Permissions Summary Section
        if permissions_summary and "error" not in permissions_summary:
            md += f"""## 🔐 Permissions Summary

**Total Endpoints:** {permissions_summary.get('total_endpoints', 0)}

"""
            # Unregistered endpoints
            unregistered = permissions_summary.get('unregistered', [])
            if unregistered:
                md += f"### 🌐 Unregistered (No Auth Required)\n\n"
                md += f"**Count:** {len(unregistered)}\n\n"
                for item in unregistered:
                    md += f"- **{item['method']}** `{item['endpoint']}`\n"
                md += "\n"
            
            # Role-specific endpoints
            roles = permissions_summary.get('roles', {})
            for role_name in sorted(roles.keys()):
                endpoints = roles[role_name]
                md += f"### 👤 {role_name.title()}\n\n"
                md += f"**Count:** {len(endpoints)}\n\n"
                for item in endpoints:
                    roles_str = ', '.join(item['roles'])
                    md += f"- **{item['method']}** `{item['endpoint']}` - Roles: {roles_str}\n"
                md += "\n"

        md += "---\n\n*Report generated by StreamA2026 Test System*\n"
        return md


if __name__ == "__main__":
    # Test the reporter
    project_dir = Path(__file__).parent.parent.parent
    reporter = CoverageReporter(str(project_dir))
    
    # Generate sample report
    api_coverage = {
        "total_backend_endpoints": 52,
        "covered_count": 45,
        "covered_percentage": 86.5,
        "unused_count": 7,
        "unused_percentage": 13.5,
        "new_endpoints_count": 2,
        "new_endpoints": [
            {"method": "GET", "path": "/api/test", "file": "test.py", "line": 10}
        ],
        "unused_endpoints": [
            {"method": "POST", "path": "/api/unused", "file": "unused.py", "line": 5}
        ]
    }
    
    report_path = reporter.generate_comprehensive_report(api_coverage=api_coverage)
    print(f"Report generated: {report_path}")
