"""Azure Data Factory (ADF) evaluator for scoring submissions."""

from typing import Any, Dict


def evaluate_adf_submission(metadata: Dict[str, Any]) -> Dict[str, Any]:
    """Score an ADF submission based on structure and completeness.

    Rubric (out of 100):
    - 30 points: Valid ADF structure detected (source_type present)
    - 30 points: At least 1 pipeline with >= 1 activity
    - 20 points: At least 1 linked service
    - 20 points: At least 1 dataset

    Args:
        metadata: Metadata dictionary from extract_adf_metadata()

    Returns:
        Dictionary with 'score' (0-100) and 'feedback' (humanized string)
    """
    score = 0
    feedback_lines = []

    # Criterion 1: Valid ADF structure (30 points)
    source_type = metadata.get("source_type")
    if source_type:
        score += 30
        feedback_lines.append(f"[OK] Valid ADF structure detected ({source_type}).")
    else:
        feedback_lines.append("[X] No valid ADF structure detected.")

    # Criterion 2: At least 1 pipeline with activities (30 points)
    pipelines = metadata.get("pipelines", [])
    pipeline_with_activities = any(
        p.get("activity_count", 0) >= 1 for p in pipelines
    )
    if pipeline_with_activities:
        score += 30
        active_count = len([p for p in pipelines if p.get("activity_count", 0) >= 1])
        feedback_lines.append(f"[OK] Found {active_count} pipeline(s) with activity definitions.")
    else:
        if pipelines:
            feedback_lines.append(f"[X] Found {len(pipelines)} pipeline(s), but none contain activities.")
        else:
            feedback_lines.append("[X] No pipelines found with activity definitions.")

    # Criterion 3: At least 1 linked service (20 points)
    linked_services = metadata.get("linked_services", [])
    if linked_services:
        score += 20
        service_types = set(s.get("type", "Unknown") for s in linked_services)
        types_str = ", ".join(sorted(service_types))
        feedback_lines.append(
            f"[OK] Found {len(linked_services)} linked service(s) "
            f"(types: {types_str})."
        )
    else:
        feedback_lines.append("[X] No linked services found.")

    # Criterion 4: At least 1 dataset (20 points)
    datasets = metadata.get("datasets", [])
    if datasets:
        score += 20
        dataset_types = set(d.get("type", "Unknown") for d in datasets)
        types_str = ", ".join(sorted(dataset_types))
        feedback_lines.append(
            f"[OK] Found {len(datasets)} dataset(s) "
            f"(types: {types_str})."
        )
    else:
        feedback_lines.append("[X] No datasets found.")

    # Additional context
    params = metadata.get("parameters", [])
    if params:
        feedback_lines.append(f"\n[i] Additional: {len(params)} parameter(s) defined.")

    # Summary
    feedback_lines.append("")
    feedback_lines.append(f"Total Score: {score}/100")

    if score == 100:
        summary = "Excellent work! Your ADF submission has all required components well-structured."
    elif score >= 80:
        summary = "Good submission. Your ADF has most required components. Consider adding missing parts."
    elif score >= 50:
        summary = "Partial submission. Several required ADF components are missing."
    else:
        summary = "Incomplete submission. Please ensure your ADF includes pipelines, datasets, and linked services."

    feedback_lines.append(summary)

    feedback = "\n".join(feedback_lines)

    return {
        "score": score,
        "feedback": feedback
    }
