"""Quality assessment for enhancement service."""

import re
from typing import List


def calculate_confidence(original: str, enhanced: str) -> float:
    """Calculate confidence score for enhancement.

    Args:
        original: Original transcript
        enhanced: Enhanced transcript

    Returns:
        Confidence score between 0 and 1

    """
    if not enhanced or not original:
        return 0.0

    # Length-based confidence (good enhancements should be similar in length)
    length_ratio = len(enhanced) / len(original)
    
    if 0.8 <= length_ratio <= 1.3:
        length_score = 0.95
    elif 0.5 <= length_ratio <= 2.0:
        length_score = 0.7
    else:
        length_score = 0.5

    # Content similarity score
    original_words = set(original.lower().split())
    enhanced_words = set(enhanced.lower().split())
    
    if not original_words:
        similarity_score = 0.0
    else:
        intersection = original_words.intersection(enhanced_words)
        similarity_score = len(intersection) / len(original_words)

    # Improvement detection score
    improvements = identify_improvements(original, enhanced)
    improvement_score = min(len(improvements) * 0.1, 0.3)  # Max 0.3 for improvements

    # Weighted combination
    confidence = (length_score * 0.3 + similarity_score * 0.5 + improvement_score * 0.2)
    
    return min(confidence, 1.0)


def identify_improvements(original: str, enhanced: str) -> List[str]:
    """Identify what improvements were made.

    Args:
        original: Original transcript
        enhanced: Enhanced transcript

    Returns:
        List of improvement types detected

    """
    improvements = []

    # Check for punctuation improvements
    if enhanced.count(".") > original.count("."):
        improvements.append("punctuation")

    # Check for capitalization
    if enhanced and original and enhanced[0].isupper() and not original[0].isupper():
        improvements.append("capitalization")

    # Check for paragraph formatting
    if "\n\n" in enhanced and "\n\n" not in original:
        improvements.append("formatting")

    # Check for technical term improvements
    tech_terms = ["python", "javascript", "react", "api", "sql", "html", "css"]
    for term in tech_terms:
        if term.lower() in original.lower() and term.title() in enhanced:
            improvements.append("technical_terms")
            break

    # Check for number preservation
    original_numbers = re.findall(r'\d+', original)
    enhanced_numbers = re.findall(r'\d+', enhanced)
    if original_numbers and enhanced_numbers and len(original_numbers) == len(enhanced_numbers):
        improvements.append("number_preservation")

    return list(set(improvements))  # Remove duplicates
