import random
from datetime import timedelta

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone

from trees.models import Activity, Asset, Organization, Profile, Species

LAT_RANGE = (-1.5, 0.5)
LON_RANGE = (36.5, 37.5)
COUNTIES = ["Nairobi", "Kiambu", "Murang'a", "Nyeri", "Machakos"]


class Command(BaseCommand):
    help = "Seed demo data for the JM3 platform (Asset-based)."

    def handle(self, *args, **options):
        admin, created = User.objects.get_or_create(
            username="admin", defaults={"email": "admin@jm3.africa", "is_staff": True, "is_superuser": True}
        )
        if created:
            admin.set_password("admin12345")
            admin.save()
            self.stdout.write("Created superuser 'admin' / 'admin12345'")

        org_data = [("Greenwood Academy", "school", "Nairobi"),
                    ("Green Belt Movement", "ngo", "Kiambu"),
                    ("Nyeri County Forestry", "county", "Nyeri")]
        orgs = []
        for name, otype, county in org_data:
            org, _ = Organization.objects.get_or_create(name=name, defaults={"org_type": otype, "county": county})
            orgs.append(org)

        Profile.objects.update_or_create(user=admin, defaults={"role": "jm3_admin", "organization": orgs[0]})

        species_data = [
            ("Grevillea robusta", "Grevillea robusta", False, 8.0),
            ("Croton megalocarpus", "Croton megalocarpus", True, 12.0),
            ("Acacia (Vachellia spp.)", "Vachellia spp.", True, 9.0),
            ("Mango", "Mangifera indica", False, 7.0),
            ("Cedar (Mukurwe)", "Juniperus procera", True, 15.0),
        ]
        species_objs = []
        for common, sci, indigenous, factor in species_data:
            sp, _ = Species.objects.get_or_create(
                common_name=common,
                defaults={"scientific_name": sci, "is_indigenous": indigenous, "carbon_factor_kg_per_year": factor})
            species_objs.append(sp)

        # Nurseries as assets
        nurseries = []
        for name, owner, cap in [("Highland Greens Nursery", "Jane Wanjiru", 50000),
                                 ("Riverside Seedlings", "Peter Otieno", 20000),
                                 ("Mt Kenya Indigenous Nursery", "Samuel Kariuki", 35000)]:
            n, _ = Asset.objects.get_or_create(
                asset_type="nursery", name=name,
                defaults={"owner_name": owner, "seedling_capacity": cap,
                          "latitude": round(random.uniform(*LAT_RANGE), 6),
                          "longitude": round(random.uniform(*LON_RANGE), 6),
                          "county": random.choice(COUNTIES), "organization": random.choice(orgs),
                          "registered_by": admin, "verification_status": "verified"})
            n.species_available.set(random.sample(species_objs, 3))
            nurseries.append(n)

        if Asset.objects.filter(asset_type="tree").count() >= 50:
            self.stdout.write("Demo trees already seeded.")
            return

        health_weights = [("alive", 0.6), ("stressed", 0.2), ("dead", 0.15), ("unknown", 0.05)]
        verif_weights = [("verified", 0.6), ("pending", 0.3), ("suspicious", 0.1)]
        now = timezone.now()
        for i in range(60):
            org = random.choice(orgs)
            sp = random.choice(species_objs)
            nursery = random.choice(nurseries)
            health = random.choices([h for h, _ in health_weights], weights=[w for _, w in health_weights])[0]
            verif = random.choices([v for v, _ in verif_weights], weights=[w for _, w in verif_weights])[0]
            planted = timezone.localdate() - timedelta(days=random.randint(30, 700))
            tree = Asset.objects.create(
                asset_type="tree", organization=org, species=sp, source_nursery=nursery,
                latitude=round(random.uniform(*LAT_RANGE), 6), longitude=round(random.uniform(*LON_RANGE), 6),
                county=random.choice(COUNTIES), planted_date=planted, health_status=health,
                verification_status=verif,
                verification_notes="Possible duplicate location" if verif == "suspicious" else "",
                registered_by=admin)
            # planted activity (in the past)
            planted_dt = now - timedelta(days=random.randint(60, 700))
            Activity.objects.create(asset=tree, activity_type="planted", user=admin,
                                    note="Planted & registered", created_at=planted_dt)
            # an older observation so the task engine flags it as needing a check
            obs_dt = planted_dt + timedelta(days=random.randint(10, 40))
            Activity.objects.create(asset=tree, activity_type="observed", user=admin, health_status=health,
                                    height_cm=round(random.uniform(20, 150), 1),
                                    note="Seeded demo observation", created_at=obs_dt)

        self.stdout.write(self.style.SUCCESS(
            f"Seeded {len(orgs)} orgs, {len(nurseries)} nurseries, 60 tree assets with activities."))
