"""Seed default feedback channels, a tracer study, course evaluations, and
a handful of sample submissions.

Idempotent. ReportReview channels for published reports are seeded by the
``mel_report_published`` receiver, not here — this seeder focuses on the
standing channels (beneficiary / alumni / industry / Moodle) that exist
independently of individual reports.
"""
from __future__ import annotations

import logging
from datetime import date, timedelta
from decimal import Decimal

from apps.mel.feedback.models import (
    CourseEvaluation,
    FeedbackChannel,
    FeedbackChannelType,
    FeedbackSeverity,
    FeedbackStatus,
    FeedbackSubmission,
    TracerResponse,
    TracerStudy,
)

logger = logging.getLogger(__name__)


# (slug, type, name, description, is_public)
_CHANNELS: list[tuple[str, str, str, str, bool]] = [
    (
        "beneficiary-voice",
        FeedbackChannelType.BENEFICIARY,
        "Beneficiary voice",
        "Always-on public intake for scholars, grantees, and learners to share outcomes, issues, and suggestions.",
        True,
    ),
    (
        "industry-partners",
        FeedbackChannelType.INDUSTRY,
        "Industry &amp; employer feedback",
        "Structured feedback from industry partners on graduate readiness and internship performance.",
        False,
    ),
    (
        "alumni-pulse",
        FeedbackChannelType.ALUMNI,
        "Alumni pulse",
        "Rolling alumni feedback on career trajectories and institutional support.",
        True,
    ),
    (
        "rep-course-evaluations",
        FeedbackChannelType.MOODLE,
        "REP course evaluations",
        "Automated ingest of course-evaluation results from the Regional E-Learning Platform (REP).",
        False,
    ),
    (
        "mel-suggestions",
        FeedbackChannelType.GENERIC,
        "M&amp;EL suggestions",
        "Internal staff suggestions on the M&amp;EL system itself — requested indicators, UI improvements, etc.",
        False,
    ),
]


# (channel_slug, submitter_name, submitter_email, rating, severity, narrative, status)
_SUBMISSIONS: list[tuple[str, str, str, int | None, str, str, str]] = [
    (
        "beneficiary-voice",
        "Anna Nabirye",
        "anna.n@example.org",
        4,
        FeedbackSeverity.LOW,
        "The scholarship has enabled me to publish my first-author paper. Strongly recommend expanding the cohort size.",
        FeedbackStatus.NEW,
    ),
    (
        "beneficiary-voice",
        "Kwame Otieno",
        "kwame.o@example.org",
        2,
        FeedbackSeverity.HIGH,
        "Stipend disbursement was 2 months late, which forced me to skip a field trip. Please streamline the payment process.",
        FeedbackStatus.TRIAGED,
    ),
    (
        "industry-partners",
        "Mbeki Agro Ltd",
        "hr@mbeki-agro.example",
        5,
        FeedbackSeverity.LOW,
        "Our 2025 intern cohort from RUFORUM had strong quantitative skills but needed more exposure to commercial agronomy. Very satisfied overall.",
        FeedbackStatus.NEW,
    ),
    (
        "alumni-pulse",
        "Dr. Fatou Sy",
        "fatou.sy@example.org",
        4,
        FeedbackSeverity.MEDIUM,
        "Tracer follow-ups arrived on time, but the questionnaire could be shorter and mobile-friendly. Currently 18 min on a slow 3G connection.",
        FeedbackStatus.NEW,
    ),
    (
        "rep-course-evaluations",
        "",
        "",
        None,
        FeedbackSeverity.LOW,
        "Auto-ingested summary — 42 learners rated 'Introduction to Agri-Food Value Chains' an average of 4.1/5 with positive qualitative feedback on case studies.",
        FeedbackStatus.NEW,
    ),
]


def _seed_channels() -> dict[str, FeedbackChannel]:
    channels: dict[str, FeedbackChannel] = {}
    for slug, type_, name, description, is_public in _CHANNELS:
        channel, _ = FeedbackChannel.objects.get_or_create(
            slug=slug,
            defaults={
                "type": type_,
                "name": name,
                "description": description,
                "is_public": is_public,
                "is_active": True,
                "token": FeedbackChannel.generate_token(),
            },
        )
        channels[slug] = channel
    logger.info("mel.seed feedback channels=%s", len(channels))
    return channels


def _seed_submissions(channels: dict[str, FeedbackChannel]) -> None:
    from apps.mel.feedback.services import submit_feedback

    for slug, name, email, rating, severity, narrative, status in _SUBMISSIONS:
        channel = channels.get(slug)
        if channel is None:
            continue
        submission_key = f"seed:{slug}:{email or name}"
        submission, created = submit_feedback(
            channel=channel,
            narrative=narrative,
            submitter_name=name,
            submitter_email=email,
            rating=rating,
            severity=severity,
            submission_key=submission_key,
        )
        # Force the target status if seed data wants e.g. TRIAGED.
        if created and submission.status != status:
            submission.status = status
            submission.save(update_fields=["status"])


def _seed_tracer_study() -> None:
    study, created = TracerStudy.objects.get_or_create(
        slug="phd-cohort-2023-tracer",
        defaults={
            "name": "PhD cohort 2023 tracer",
            "description": (
                "Three-year tracer follow-up on the 2023 PhD cohort — career trajectory, "
                "publications, and contribution to national agri-food research."
            ),
            "target_population": "PhD scholarship recipients graduating 2023.",
            "opens_at": date.today() - timedelta(days=30),
            "closes_at": date.today() + timedelta(days=120),
        },
    )
    if not created:
        return
    # A handful of sample responses.
    responses = [
        dict(
            email="grad1@example.org",
            name="Dr. Anne Muwonge",
            employment_status="Employed — public research",
            employer="Makerere University",
            role="Assistant Lecturer",
            salary_band="band-4",
        ),
        dict(
            email="grad2@example.org",
            name="Dr. Samuel Eze",
            employment_status="Employed — private sector",
            employer="West Africa Seed Co.",
            role="Plant breeder",
            salary_band="band-5",
        ),
        dict(
            email="grad3@example.org",
            name="Dr. Chipo Ndlovu",
            employment_status="Self-employed",
            employer="Own consultancy",
            role="Agri-business advisor",
            salary_band="band-3",
        ),
    ]
    for r in responses:
        TracerResponse.objects.create(
            study=study,
            respondent_email=r["email"],
            respondent_name=r["name"],
            employment_status=r["employment_status"],
            employer=r["employer"],
            role=r["role"],
            salary_band=r["salary_band"],
            payload=r,
        )


def _seed_course_evaluations() -> None:
    today = date.today()
    period = f"{today.year}-Q{(today.month - 1) // 3 + 1}"
    samples = [
        ("intro-agri-food-value-chains", "Introduction to Agri-Food Value Chains", Decimal("4.1"), 42),
        ("research-methods", "Research Methods for Agri-Food Systems", Decimal("4.4"), 28),
        ("climate-smart-agronomy", "Climate-Smart Agronomy", Decimal("3.8"), 56),
    ]
    for slug, name, score, count in samples:
        CourseEvaluation.objects.update_or_create(
            source_system="moodle",
            course_slug=slug,
            period_label=period,
            defaults={
                "course_name": name,
                "aggregate_score": score,
                "response_count": count,
                "payload": {"sample": True},
            },
        )


def seed_feedback() -> None:
    channels = _seed_channels()
    _seed_submissions(channels)
    _seed_tracer_study()
    _seed_course_evaluations()
