"""Canonical ESG innovation-evaluation rubric (the "Group one" evaluation rubric).

A two-level rubric: six weighted **categories**, each holding several scored
**criteria**. Every criterion is scored on a 1–5 scale and carries the five
descriptive score anchors judges use to calibrate. The criteria's points sum to
100, so each 5-point criterion contributes a fractional ``weight`` of 0.05 and
the weights across all criteria sum to exactly 1.0 (the publish gate).

This module is the single source of truth for the standard rubric — the seeder
and the "Apply ESG standard rubric" admin action both build from ``ESG_RUBRIC``
via :func:`apply_esg_rubric`.
"""
from __future__ import annotations

from decimal import Decimal
from typing import TYPE_CHECKING

if TYPE_CHECKING:  # pragma: no cover - typing only
    from apps.smehub.showcasing.models import ChallengeScoringRubric


def _anchors(five: str, four: str, three: str, two: str, one: str) -> dict[str, str]:
    return {"5": five, "4": four, "3": three, "2": two, "1": one}


# Each criterion is worth 5 points (max_marks=5). weight is filled in per
# criterion by apply_esg_rubric as points/100 so all weights sum to 1.0.
ESG_RUBRIC: list[dict] = [
    {
        "title": "Scientific Foundation and Innovation",
        "points": 20,
        "criteria": [
            {
                "title": "Scientific Rigor",
                "anchors": _anchors(
                    "Solution based on solid scientific principles with clear methodology",
                    "Good scientific foundation with minor methodological gaps",
                    "Adequate scientific basis but needs strengthening",
                    "Weak scientific foundation, requires significant improvement",
                    "Minimal or flawed scientific approach",
                ),
            },
            {
                "title": "Innovation Level",
                "anchors": _anchors(
                    "Highly innovative solution addressing problem in novel way",
                    "Good innovation with some novel elements",
                    "Moderate innovation with incremental improvements",
                    "Limited innovation, mostly existing solutions",
                    "No significant innovation, replicates existing approaches",
                ),
            },
            {
                "title": "Technical Feasibility",
                "anchors": _anchors(
                    "Technically sound with clear implementation pathway",
                    "Mostly feasible with minor technical challenges",
                    "Feasible but requires technical development",
                    "Significant technical challenges to overcome",
                    "Technical approach is unclear or unfeasible",
                ),
            },
            {
                "title": "Intellectual Property Potential",
                "anchors": _anchors(
                    "Strong IP potential with clear protection strategy",
                    "Good IP potential, some protection possible",
                    "Moderate IP potential, limited protection",
                    "Minimal IP potential",
                    "No clear IP potential or protection strategy",
                ),
            },
        ],
    },
    {
        "title": "Market Potential and Problem Solving",
        "points": 25,
        "criteria": [
            {
                "title": "Problem Significance",
                "anchors": _anchors(
                    "Addresses critical societal problem with significant impact potential",
                    "Addresses important problem with good impact potential",
                    "Addresses relevant problem with moderate impact",
                    "Addresses minor problem with limited impact",
                    "Problem significance unclear or minimal",
                ),
            },
            {
                "title": "Market Size and Demand",
                "anchors": _anchors(
                    "Large market with demonstrated strong demand",
                    "Good market size with evidence of demand",
                    "Moderate market with some demand indication",
                    "Small market with uncertain demand",
                    "Unclear market or no evidence of demand",
                ),
            },
            {
                "title": "Customer Validation",
                "anchors": _anchors(
                    "Strong customer validation with confirmed willingness to pay",
                    "Good customer feedback with likely adoption",
                    "Some customer validation, needs more confirmation",
                    "Limited customer interaction, uncertain reception",
                    "No customer validation conducted",
                ),
            },
            {
                "title": "Competitive Advantage",
                "anchors": _anchors(
                    "Clear, sustainable competitive advantage",
                    "Good competitive positioning with some advantages",
                    "Moderate competitive position",
                    "Weak competitive position, easily replicable",
                    "No clear competitive advantage",
                ),
            },
            {
                "title": "Social Impact Potential",
                "anchors": _anchors(
                    "Significant positive social impact with measurable outcomes",
                    "Good social impact potential",
                    "Moderate social benefits",
                    "Limited social impact",
                    "Unclear or minimal social benefits",
                ),
            },
        ],
    },
    {
        "title": "Business Model and Financial Viability",
        "points": 20,
        "criteria": [
            {
                "title": "Revenue Model Clarity",
                "anchors": _anchors(
                    "Clear, realistic revenue model with multiple streams",
                    "Good revenue model with minor uncertainties",
                    "Basic revenue model needs development",
                    "Unclear revenue model, significant gaps",
                    "No clear revenue model",
                ),
            },
            {
                "title": "Cost Structure Understanding",
                "anchors": _anchors(
                    "Comprehensive understanding of all costs with realistic projections",
                    "Good cost understanding with minor gaps",
                    "Basic cost structure identified",
                    "Limited cost understanding",
                    "Poor or no cost analysis",
                ),
            },
            {
                "title": "Financial Projections",
                "anchors": _anchors(
                    "Realistic, well-researched financial projections",
                    "Good projections with reasonable assumptions",
                    "Basic projections need refinement",
                    "Unrealistic or poorly supported projections",
                    "No meaningful financial projections",
                ),
            },
            {
                "title": "Scalability Potential",
                "anchors": _anchors(
                    "High scalability with clear growth strategy",
                    "Good scalability potential",
                    "Moderate scalability",
                    "Limited scalability",
                    "Poor scalability potential",
                ),
            },
        ],
    },
    {
        "title": "Team Capability and Execution",
        "points": 15,
        "criteria": [
            {
                "title": "Team Composition and Skills",
                "anchors": _anchors(
                    "Well-rounded team with complementary skills",
                    "Good team with most necessary skills",
                    "Adequate team, some skill gaps",
                    "Weak team composition, significant gaps",
                    "Poor team structure or major skill deficiencies",
                ),
            },
            {
                "title": "Leadership and Communication",
                "anchors": _anchors(
                    "Strong leadership with excellent communication skills",
                    "Good leadership and communication",
                    "Adequate leadership, needs improvement",
                    "Weak leadership or poor communication",
                    "Poor leadership and communication skills",
                ),
            },
            {
                "title": "Execution Track Record",
                "anchors": _anchors(
                    "Strong track record of delivering results",
                    "Good execution experience",
                    "Some execution experience",
                    "Limited execution experience",
                    "No clear execution track record",
                ),
            },
        ],
    },
    {
        "title": "TVET Integration and Manufacturing Potential",
        "points": 10,
        "criteria": [
            {
                "title": "Manufacturing Feasibility",
                "anchors": _anchors(
                    "Excellent fit for TVET manufacturing capabilities",
                    "Good manufacturing potential with TVET partners",
                    "Moderate manufacturing requirements, some TVET capability",
                    "Limited TVET manufacturing applicability",
                    "Poor fit for TVET manufacturing",
                ),
            },
            {
                "title": "Job Creation Potential",
                "anchors": _anchors(
                    "High potential for creating multiple TVET jobs",
                    "Good job creation potential",
                    "Moderate job creation opportunity",
                    "Limited job creation potential",
                    "Minimal or no job creation opportunity",
                ),
            },
        ],
    },
    {
        "title": "Presentation Quality and Pitch Effectiveness",
        "points": 10,
        "criteria": [
            {
                "title": "Clarity and Organization",
                "anchors": _anchors(
                    "Exceptionally clear, well-organized presentation",
                    "Clear presentation with good organization",
                    "Adequate clarity and organization",
                    "Somewhat unclear or poorly organized",
                    "Poor clarity and organization",
                ),
            },
            {
                "title": "Persuasiveness and Passion",
                "anchors": _anchors(
                    "Highly persuasive with demonstrated passion",
                    "Good persuasiveness and enthusiasm",
                    "Adequate persuasiveness",
                    "Limited persuasiveness",
                    "Poor persuasiveness or lack of passion",
                ),
            },
        ],
    },
]

# Points every criterion is worth on the 1–5 scale.
CRITERION_MAX_MARKS = 5
# Total points across the whole rubric (used to derive fractional weights).
TOTAL_POINTS = sum(cat["points"] for cat in ESG_RUBRIC)  # 100


def apply_esg_rubric(rubric: "ChallengeScoringRubric") -> None:
    """(Re)provision ``rubric`` with the canonical ESG hierarchy.

    Idempotent-by-replacement: any existing categories and criteria on the
    rubric are cleared first, so calling this twice yields the same result and
    never double-seeds. Criterion weights are derived as ``max_marks / 100`` so
    they sum to exactly 1.0.
    """
    from apps.smehub.showcasing.models import (
        ChallengeRubricCategory,
        ChallengeRubricSection,
    )

    rubric.sections.all().delete()
    rubric.categories.all().delete()

    weight = (Decimal(CRITERION_MAX_MARKS) / Decimal(TOTAL_POINTS)).quantize(Decimal("0.0001"))
    order = 0
    for cat_order, cat in enumerate(ESG_RUBRIC):
        category = ChallengeRubricCategory.objects.create(
            rubric=rubric,
            title=cat["title"],
            points=cat["points"],
            order=cat_order,
        )
        for crit in cat["criteria"]:
            ChallengeRubricSection.objects.create(
                rubric=rubric,
                category=category,
                title=crit["title"],
                weight=weight,
                max_marks=CRITERION_MAX_MARKS,
                score_anchors=crit["anchors"],
                order=order,
            )
            order += 1
