"""HTML report generator for Compliance Copilot."""

from pathlib import Path
from datetime import datetime
from jinja2 import Environment, FileSystemLoader
from ..engine import RuleStatus
from ..version import get_version

class HtmlReporter:
    """Generates an HTML report from scan results."""
    
    def __init__(self, template_dir=None):
        """Initialize the HTML reporter.
        
        Args:
            template_dir: Path to templates folder. If None, uses default.
        """
        if template_dir is None:
            # Assume templates are in 'templates' folder at project root
            template_dir = Path(__file__).parent.parent.parent.parent / 'templates'
        
        self.env = Environment(
            loader=FileSystemLoader(str(template_dir)),
            autoescape=True
        )
        self.template = self.env.get_template('report.html')
    
    def generate(self, results, output_path):
        """Generate HTML report and save to output_path.
        
        Args:
            results: List of RuleResult objects
            output_path: Where to save the HTML file
        """
        # Prepare data for template
        total = len(results)
        passed = sum(1 for r in results if r.status == RuleStatus.PASS)
        failed = sum(1 for r in results if r.status == RuleStatus.FAIL)
        errors = sum(1 for r in results if r.status == RuleStatus.ERROR)
        
        # Convert results to dict for template
        results_data = []
        for r in results:
            r_dict = {
                'rule_id': r.rule_id,
                'rule_name': r.rule_name,
                'status': r.status.value,
                'pass_rate': r.pass_rate,
                'total_rows': r.total_rows,
                'passed_rows': r.passed_rows,
                'failed_rows': r.failed_rows,
                'error_message': r.error_message,
                'description': getattr(r, 'description', ''),
                'violations': r.violations,
            }
            results_data.append(r_dict)
        
        # Render HTML
        html = self.template.render(
            summary={
                'total': total,
                'passed': passed,
                'failed': failed,
                'errors': errors
            },
            results=results_data,
            timestamp=datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC'),
            version=get_version()
        )
        
        # Write to file
        with open(output_path, 'w') as f:
            f.write(html)
        
        return output_path
