"""Seed SME-Hub onboarding (SP1) demo data.

Idempotent.  Creates a representative spread:

* 6 entrepreneurs across the verification states (4 verified incl. a
  multi-business / multi-AIH case, 1 pending, 1 rejected — gives admins
  realistic queue traffic to play with).
* 4 mentors, 3 investors, 5 service providers, 3 partners, 3 buyers — each
  role used downstream by SP3 / SP4 / SP5.
* 8 businesses across sectors and stages, all with a baseline; verified
  ones get an AIH affiliation that locks the baseline.
"""
from __future__ import annotations

import logging
from datetime import date

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.db import transaction
from django.utils import timezone

from apps.core.authentication.models import Institution
from apps.core.countries import to_country_name
from apps.core.permissions.roles import UserRole
from apps.smehub.onboarding.models import (
    AIHAffiliation,
    Business,
    BusinessBaseline,
    BusinessStage,
    BuyerProfile,
    EntrepreneurProfile,
    InvestorProfile,
    MentorProfile,
    PartnerProfile,
    RevenueRange,
    ServiceProviderProfile,
)

logger = logging.getLogger(__name__)
User = get_user_model()

DEMO_PASSWORD = "smehub-demo-2026"  # noqa: S105 - demo only


def _ensure_user(email: str, *, first: str, last: str, role: str) -> User:
    user, created = User.objects.get_or_create(
        email=email,
        defaults={
            "first_name": first,
            "last_name": last,
            "is_active": True,
            "email_verified": True,
            "role": role,
        },
    )
    if created:
        user.password = make_password(DEMO_PASSWORD)
        user.save(update_fields=["password"])
    return user


def _ensure_institution(name: str, country: str) -> Institution:
    inst, _ = Institution.objects.get_or_create(
        name=name,
        defaults={"country": to_country_name(country), "is_member": True, "is_active": True},
    )
    return inst


_ENTREPRENEURS = [
    ("Asha", "Ndlovu", "asha.ndlovu@smehub.example", "ZW", "Bulawayo AgriCo", "verified"),
    ("Boniface", "Wanyama", "boniface.wanyama@smehub.example", "UG", "GreenSeed Uganda", "verified"),
    ("Chimene", "Kayitare", "chimene.kayitare@smehub.example", "RW", "Hilltop Honey Coop", "verified"),
    ("Daniel", "Otieno", "daniel.otieno@smehub.example", "KE", "AquaFarms East Africa", "verified"),
    ("Elif", "Demir", "elif.demir@smehub.example", "ET", "Solar Agro Solutions", "pending"),
    ("Fatuma", "Said", "fatuma.said@smehub.example", "TZ", "Coastal Spice Traders", "rejected"),
]

_MENTORS = [
    ("Geoffrey", "Mwangi", "geoffrey.mentor@smehub.example", "KE", "EAC Innovation Hub"),
    ("Hannah", "Kebede", "hannah.mentor@smehub.example", "ET", "Addis Ababa University"),
    ("Ibrahim", "Conteh", "ibrahim.mentor@smehub.example", "SN", "BCEAO Innovation Lab"),
    ("Joyce", "Akinyi", "joyce.mentor@smehub.example", "UG", "Makerere AIH"),
]
_INVESTORS = [
    ("Karim", "Salim", "karim.invest@smehub.example", "EG", "Nile Capital"),
    ("Lerato", "Pule", "lerato.invest@smehub.example", "ZA", "Sahel Impact Fund"),
    ("Mariam", "Ouattara", "mariam.invest@smehub.example", "CI", "African Agri Capital"),
]
_SERVICES = [
    ("Naomi", "Adeyemi", "naomi.svc@smehub.example", "NG", "Lagos Legal Group"),
    ("Otieno", "Ojwang", "otieno.svc@smehub.example", "KE", "EastAfri QA Lab"),
    ("Patricia", "Mensah", "patricia.svc@smehub.example", "GH", "Accra Branding House"),
    ("Quincy", "Nguema", "quincy.svc@smehub.example", "CM", "CFA Tax Advisors"),
    ("Ruth", "Sserunjogi", "ruth.svc@smehub.example", "UG", "AfriCert Certification"),
]
_PARTNERS = [
    ("Sahel", "AgriHub", "partner.sahel@smehub.example", "BF", "Sahel AgriHub"),
    ("EastAfri", "Coalition", "partner.eastafri@smehub.example", "TZ", "EastAfri Innovation"),
    ("West", "GAP", "partner.west@smehub.example", "NG", "West Africa GAP"),
]
_BUYERS = [
    ("Trade", "Continental", "buyer.trade@smehub.example", "KE", "Continental Trade Co."),
    ("Coop", "Buyer", "buyer.coop@smehub.example", "UG", "Coop Wholesale"),
    ("Export", "Africa", "buyer.export@smehub.example", "GH", "Export Africa Ltd."),
]

_BUSINESSES = [
    ("asha.ndlovu@smehub.example", "Bulawayo AgriCo", "Agriculture", "Smallholder grain", BusinessStage.GROWTH, "ZW", "Bulawayo", 12, 6, RevenueRange.R_10K_50K, "ZW, ZM"),
    ("boniface.wanyama@smehub.example", "GreenSeed Maize", "Agriculture", "Seed production", BusinessStage.EARLY_REVENUE, "UG", "Mbale", 6, 4, RevenueRange.R_1K_10K, "UG"),
    ("boniface.wanyama@smehub.example", "GreenSeed Beans", "Agriculture", "Pulse seed", BusinessStage.MVP, "UG", "Mbale", 2, 1, RevenueRange.UNDER_1K, "UG"),
    ("chimene.kayitare@smehub.example", "Hilltop Honey", "Agribusiness", "Apiculture", BusinessStage.GROWTH, "RW", "Musanze", 8, 5, RevenueRange.R_10K_50K, "RW, BI"),
    ("daniel.otieno@smehub.example", "AquaFarms", "Aquaculture", "Tilapia", BusinessStage.EARLY_REVENUE, "KE", "Kisumu", 10, 3, RevenueRange.R_10K_50K, "KE, UG"),
    ("elif.demir@smehub.example", "Solar Agro", "Energy", "Solar irrigation kits", BusinessStage.MVP, "ET", "Addis Ababa", 4, 2, RevenueRange.UNDER_1K, "ET"),
    ("fatuma.said@smehub.example", "Coastal Spices", "Agribusiness", "Spice processing", BusinessStage.IDEA, "TZ", "Zanzibar", 1, 1, RevenueRange.NONE, "TZ"),
]

_INSTITUTIONS = [
    ("Makerere University", "UG"),
    ("University of Nairobi", "KE"),
    ("Addis Ababa University", "ET"),
    ("Sokoine University of Agriculture", "TZ"),
    ("National University of Rwanda", "RW"),
]


@transaction.atomic
def seed() -> dict:
    counts = {"users": 0, "entrepreneurs": 0, "businesses": 0, "affiliations": 0, "role_profiles": 0}

    institutions = [_ensure_institution(name, country) for name, country in _INSTITUTIONS]

    entrepreneur_objects: dict[str, EntrepreneurProfile] = {}
    for first, last, email, country, org, status_kind in _ENTREPRENEURS:
        user = _ensure_user(email, first=first, last=last, role=UserRole.ENTREPRENEUR)
        counts["users"] += 1
        profile, created = EntrepreneurProfile.objects.get_or_create(
            user=user,
            defaults={
                "country": to_country_name(country),
                "organisation": org,
                "submitted_at": timezone.now(),
                "verification_status": EntrepreneurProfile.Status.PENDING_VERIFICATION,
            },
        )
        if created:
            counts["entrepreneurs"] += 1
        if status_kind == "verified" and profile.verification_status != EntrepreneurProfile.Status.VERIFIED:
            profile.verify(by_user=user)
            profile.save()
        elif status_kind == "rejected" and profile.verification_status != EntrepreneurProfile.Status.REJECTED:
            profile.reject(reason="Demo seed: rejected for incomplete documentation.")
            profile.save()
        entrepreneur_objects[email] = profile

    for idx, (owner_email, name, sector, sub, stage, country, location, fte, pte, rev, geo) in enumerate(_BUSINESSES):
        ep = entrepreneur_objects.get(owner_email)
        if ep is None or ep.verification_status != EntrepreneurProfile.Status.VERIFIED:
            continue
        biz, b_created = Business.objects.get_or_create(
            entrepreneur=ep,
            name=name,
            defaults={
                "sector": sector,
                "sub_sector": sub,
                "business_stage": stage,
                "founding_date": date(2022, 1, 1),
                "country": to_country_name(country),
                "location": location,
            },
        )
        if b_created:
            counts["businesses"] += 1
        if biz.verification_status != Business.Status.VERIFIED:
            biz.verify(by_user=ep.user)
            biz.save()
        BusinessBaseline.objects.update_or_create(
            business=biz,
            defaults={
                "business_stage_at_entry": stage,
                "fte_count": fte,
                "pte_count": pte,
                "revenue_range": rev,
                "geographic_reach": geo,
                "primary_target_market": geo,
            },
        )
        institution = institutions[idx % len(institutions)]
        _, a_created = AIHAffiliation.objects.get_or_create(
            business=biz,
            institution=institution,
            defaults={
                "nature": AIHAffiliation.AffiliationNature.ALUMNI,
                "programme_of_origin": "RUFORUM AIH demo seed",
                "is_primary": True,
            },
        )
        if a_created:
            counts["affiliations"] += 1
        if biz.baseline.locked_at is None:
            biz.baseline.locked_at = timezone.now()
            biz.baseline.save(update_fields=["locked_at", "updated_at"])

    role_data = (
        (_MENTORS, MentorProfile, UserRole.MENTOR, {"expertise_sectors": ["agriculture", "agribusiness"], "languages": ["English"], "years_experience": 8}),
        (_INVESTORS, InvestorProfile, UserRole.INVESTOR, {"organisation_type": "VC"}),
        (_SERVICES, ServiceProviderProfile, UserRole.SERVICE_PROVIDER, {"services_offered": ["legal", "certification", "tax"]}),
        (_PARTNERS, PartnerProfile, UserRole.PARTNER, {"organisation_type": "ngo"}),
        (_BUYERS, BuyerProfile, UserRole.BUYER, {"sectors_sourced": ["agriculture"]}),
    )
    for entries, model, role, extras in role_data:
        for first, last, email, country, org in entries:
            user = _ensure_user(email, first=first, last=last, role=role)
            counts["users"] += 1
            instance, created = model.objects.get_or_create(
                user=user,
                defaults={"country": to_country_name(country), "organisation": org, **extras},
            )
            counts["role_profiles"] += int(created)
            if instance.verification_status != model.Status.VERIFIED:
                instance.verify(by_user=user)
                instance.save()

    return counts
