"""
Report Service - Handles detailed test case report generation.
Generates structured reports from test execution logs.
"""

import re
import json
import os
from typing import Dict, List, Any
from pathlib import Path
from dotenv import load_dotenv

from core.logger import get_logger

load_dotenv()


class ReportService:
    """
    Service responsible for generating detailed test case reports.
    Parses log data and creates structured report outputs.
    """

    REPORTS_FOLDER = "reports"
    LATEST_REPORT_FILENAME = "latest_report.json"
    DETAILED_REPORT_FILENAME = "detailed_report.json"
    
    TEST_CASE_PATTERN = re.compile(
        r"Starting Test Case: \[(\d+)\] \[(\d+)\](.+?)\n.*?Start Time: (.+?)\n"
        r"(?:.*?Step .*? failed: (.+?))?\n.*?Completed Test Case: \[\1\] \[\2\].*?\n.*?⏳ Duration: (.+?)\n",
        re.DOTALL
    )

    def __init__(self, logger=None):
        """Initialize the report service."""
        self.logger = logger or get_logger(__name__)
        self.include_hcltech_id = str(os.getenv("HCLTech_TestCaseId", "true")).strip().lower() == "true"

    def _get_report_paths(self) -> tuple:
        """Get paths for input and output report files."""
        backend_dir = Path(__file__).resolve().parent.parent
        reports_dir = backend_dir / "reporting" / "reports" / "consolidated reports"
        log_file_path = reports_dir / self.LATEST_REPORT_FILENAME
        output_file_path = reports_dir / self.DETAILED_REPORT_FILENAME
        return str(log_file_path), str(output_file_path)

    def _build_report_columns(self) -> List[str]:
        """Build the list of column names for the detailed report."""
        columns = ["Test Case ID"]
        if self.include_hcltech_id:
            columns.append("HCLTech ADO ID")
        columns.extend(["Test Case Title", "Duration", "Status", "Failure Message"])
        return columns

    def _parse_test_case_matches(self, log_data: str) -> List[tuple]:
        """Parse test case details from log data using regex pattern."""
        return self.TEST_CASE_PATTERN.findall(log_data)

    def _create_report_row(self, match: tuple) -> Dict[str, Any]:
        """Create a report row from a regex match."""
        microsoft_id, hcltech_id, title, start_time, failure_message, duration = match
        row = {
            "Test Case ID": int(microsoft_id),
            "Test Case Title": title.strip(),
            "Duration": duration.strip(),
            "Status": "Failed" if failure_message else "Passed",
            "Failure Message": failure_message.strip() if failure_message else ""
        }
        if self.include_hcltech_id:
            row["HCLTech ADO ID"] = int(hcltech_id)
        return row

    def generate_detailed_report(self) -> Dict[str, Any]:
        """Generate a detailed report from the latest report log."""
        log_file_path, output_file_path = self._get_report_paths()
        
        try:
            with open(log_file_path, "r", encoding="utf-8") as f:
                log_data = f.read()

            matches = self._parse_test_case_matches(log_data)
            rows = [self._create_report_row(match) for match in matches]

            detailed_report = {
                "columns": self._build_report_columns(),
                "rows": rows
            }

            with open(output_file_path, "w", encoding="utf-8") as f:
                json.dump(detailed_report, f, indent=4)
            
            self.logger.info(f"Report saved to: {output_file_path}")
            return detailed_report
            
        except Exception as e:
            self.logger.error(f"Failed to generate detailed report: {e}")
            raise


# Maintain backward compatibility with function-based API
_report_service_instance = ReportService()


def generate_detailed_report() -> Dict[str, Any]:
    """
    Backward compatibility function.
    Generate a detailed report from the latest report log.
    """
    return _report_service_instance.generate_detailed_report()


__all__ = ["ReportService", "generate_detailed_report"]
