"""
Seed script — populate the database with starter agronomic data.
Run from /backend with:
    python -m app.seeds.seed
"""
import sys
import uuid
from datetime import datetime, timezone

from app.database import SessionLocal
from app.models.graft_combination import GraftCombination
from app.models.plant import Plant, RootDepthCategory, VarietyType
from app.models.soil_profile import DrainageRate, SoilProfile, SoilType, WaterRetention

# ---------------------------------------------------------------------------
# Deterministic UUIDs — makes graft_combinations easy to reference
# ---------------------------------------------------------------------------
ROMA_ID          = uuid.UUID("11111111-1111-1111-1111-111111111101")
CHERRY_ID        = uuid.UUID("11111111-1111-1111-1111-111111111102")
BEEFSTEAK_ID     = uuid.UUID("11111111-1111-1111-1111-111111111103")
BEAUFORT_ID      = uuid.UUID("11111111-1111-1111-1111-111111111104")
MAXIFORT_ID      = uuid.UUID("11111111-1111-1111-1111-111111111105")
ARNOLD_ID        = uuid.UUID("11111111-1111-1111-1111-111111111106")
BELL_PEPPER_ID   = uuid.UUID("11111111-1111-1111-1111-111111111107")
EGGPLANT_ID      = uuid.UUID("11111111-1111-1111-1111-111111111108")

ARID_SANDY_ID    = uuid.UUID("22222222-2222-2222-2222-222222222201")
MED_LOAM_ID      = uuid.UUID("22222222-2222-2222-2222-222222222202")
HEAVY_CLAY_ID    = uuid.UUID("22222222-2222-2222-2222-222222222203")
TROP_VOLCANIC_ID = uuid.UUID("22222222-2222-2222-2222-222222222204")
TEMP_ALLUVIAL_ID = uuid.UUID("22222222-2222-2222-2222-222222222205")

NOW = datetime.now(timezone.utc)


PLANTS = [
    Plant(
        id=ROMA_ID,
        name="Roma Tomato",
        species="Solanum lycopersicum",
        variety_type=VarietyType.scion,
        drought_tolerance=4,
        salinity_tolerance=4,
        heat_tolerance=6,
        cold_tolerance=3,
        disease_resistance={"fusarium": 6, "verticillium": 5, "nematode": 4},
        optimal_ph_min=6.0,
        optimal_ph_max=6.8,
        nutrient_uptake_efficiency={"N": 1.0, "P": 1.0, "K": 1.1},
        root_depth_category=RootDepthCategory.medium,
        growth_cycle_days=75,
        yield_potential_kg_per_plant=3.5,
        description=(
            "Classic paste tomato widely used in commercial greenhouse production. "
            "Firm flesh with low moisture content, excellent for processing and fresh market."
        ),
        created_at=NOW, updated_at=NOW,
    ),
    Plant(
        id=CHERRY_ID,
        name="Cherry Tomato",
        species="Solanum lycopersicum var. cerasiforme",
        variety_type=VarietyType.scion,
        drought_tolerance=5,
        salinity_tolerance=5,
        heat_tolerance=7,
        cold_tolerance=3,
        disease_resistance={"fusarium": 7, "powdery_mildew": 5, "botrytis": 4},
        optimal_ph_min=6.0,
        optimal_ph_max=7.0,
        nutrient_uptake_efficiency={"N": 0.9, "P": 1.0, "K": 1.0},
        root_depth_category=RootDepthCategory.medium,
        growth_cycle_days=60,
        yield_potential_kg_per_plant=2.0,
        description=(
            "High-sugar small-fruited tomato with good heat tolerance. "
            "Popular in warm climates; indeterminate growth habit allows long-season production."
        ),
        created_at=NOW, updated_at=NOW,
    ),
    Plant(
        id=BEEFSTEAK_ID,
        name="Beefsteak Tomato",
        species="Solanum lycopersicum",
        variety_type=VarietyType.scion,
        drought_tolerance=3,
        salinity_tolerance=3,
        heat_tolerance=5,
        cold_tolerance=2,
        disease_resistance={"fusarium": 4, "verticillium": 4, "cracking": 3},
        optimal_ph_min=6.2,
        optimal_ph_max=6.8,
        nutrient_uptake_efficiency={"N": 1.2, "P": 1.1, "K": 1.3},
        root_depth_category=RootDepthCategory.medium,
        growth_cycle_days=85,
        yield_potential_kg_per_plant=5.0,
        description=(
            "Large-fruited premium tomato requiring high nutrient input and consistent irrigation. "
            "Sensitive to stress; benefits greatly from vigorous rootstocks in challenging environments."
        ),
        created_at=NOW, updated_at=NOW,
    ),
    Plant(
        id=BEAUFORT_ID,
        name="Beaufort Rootstock",
        species="Solanum lycopersicum × Solanum habrochaites",
        variety_type=VarietyType.rootstock,
        drought_tolerance=7,
        salinity_tolerance=7,
        heat_tolerance=7,
        cold_tolerance=5,
        disease_resistance={
            "fusarium": 9, "verticillium": 9, "nematode": 8, "corky_root": 8, "tobacco_mosaic_virus": 6
        },
        optimal_ph_min=5.5,
        optimal_ph_max=7.0,
        nutrient_uptake_efficiency={"N": 1.2, "P": 1.1, "K": 1.0},
        root_depth_category=RootDepthCategory.deep,
        growth_cycle_days=90,
        yield_potential_kg_per_plant=0.0,
        description=(
            "Industry-standard tomato rootstock offering excellent disease resistance and "
            "strong vigour. Widely used in heated and unheated greenhouse production worldwide."
        ),
        created_at=NOW, updated_at=NOW,
    ),
    Plant(
        id=MAXIFORT_ID,
        name="Maxifort Rootstock",
        species="Solanum lycopersicum × Solanum habrochaites",
        variety_type=VarietyType.rootstock,
        drought_tolerance=8,
        salinity_tolerance=6,
        heat_tolerance=8,
        cold_tolerance=6,
        disease_resistance={
            "fusarium": 9, "verticillium": 9, "nematode": 9,
            "tobacco_mosaic_virus": 7, "corky_root": 7
        },
        optimal_ph_min=5.8,
        optimal_ph_max=7.2,
        nutrient_uptake_efficiency={"N": 1.3, "P": 1.2, "K": 1.1},
        root_depth_category=RootDepthCategory.deep,
        growth_cycle_days=90,
        yield_potential_kg_per_plant=0.0,
        description=(
            "Extra-vigorous rootstock suited for long-season (9–12 month) crops. "
            "Produces significantly larger root systems and higher nutrient uptake than Beaufort; "
            "best used in high-density or high-wire systems."
        ),
        created_at=NOW, updated_at=NOW,
    ),
    Plant(
        id=ARNOLD_ID,
        name="Arnold Rootstock",
        species="Solanum lycopersicum × Solanum peruvianum",
        variety_type=VarietyType.rootstock,
        drought_tolerance=6,
        salinity_tolerance=8,
        heat_tolerance=7,
        cold_tolerance=4,
        disease_resistance={
            "fusarium": 9, "verticillium": 9, "nematode": 7,
            "bacterial_wilt": 8, "corky_root": 6
        },
        optimal_ph_min=5.5,
        optimal_ph_max=7.5,
        nutrient_uptake_efficiency={"N": 1.1, "P": 1.2, "K": 1.0},
        root_depth_category=RootDepthCategory.deep,
        growth_cycle_days=85,
        yield_potential_kg_per_plant=0.0,
        description=(
            "Salinity-tolerant rootstock derived from S. peruvianum crosses. "
            "Particularly suited to coastal and arid production zones with elevated EC in irrigation water."
        ),
        created_at=NOW, updated_at=NOW,
    ),
    Plant(
        id=BELL_PEPPER_ID,
        name="California Wonder Bell Pepper",
        species="Capsicum annuum",
        variety_type=VarietyType.scion,
        drought_tolerance=4,
        salinity_tolerance=3,
        heat_tolerance=7,
        cold_tolerance=2,
        disease_resistance={"phytophthora": 5, "bacterial_spot": 5, "tobacco_mosaic_virus": 4},
        optimal_ph_min=6.0,
        optimal_ph_max=6.8,
        nutrient_uptake_efficiency={"N": 1.0, "P": 1.1, "K": 1.2},
        root_depth_category=RootDepthCategory.medium,
        growth_cycle_days=70,
        yield_potential_kg_per_plant=2.5,
        description=(
            "Blocky sweet bell pepper with broad adaptability. Grafting onto Solanaceous rootstocks "
            "can extend production season and improve tolerance in suboptimal soils."
        ),
        created_at=NOW, updated_at=NOW,
    ),
    Plant(
        id=EGGPLANT_ID,
        name="Japanese Eggplant",
        species="Solanum melongena",
        variety_type=VarietyType.scion,
        drought_tolerance=6,
        salinity_tolerance=5,
        heat_tolerance=8,
        cold_tolerance=2,
        disease_resistance={"verticillium": 4, "fusarium": 4, "bacterial_wilt": 3},
        optimal_ph_min=5.5,
        optimal_ph_max=6.8,
        nutrient_uptake_efficiency={"N": 1.1, "P": 1.0, "K": 1.0},
        root_depth_category=RootDepthCategory.medium,
        growth_cycle_days=65,
        yield_potential_kg_per_plant=3.0,
        description=(
            "Slender, tender-skinned eggplant variety preferred in Asian culinary markets. "
            "High heat tolerance makes it a strong candidate for tropical and arid grafting trials."
        ),
        created_at=NOW, updated_at=NOW,
    ),
]


SOILS = [
    SoilProfile(
        id=ARID_SANDY_ID,
        name="Arid Sandy",
        soil_type=SoilType.sandy,
        ph_level=7.8,
        organic_matter_percent=0.5,
        drainage_rate=DrainageRate.excessive,
        water_retention=WaterRetention.low,
        native_nitrogen=8.0,
        native_phosphorus=4.0,
        native_potassium=80.0,
        salinity_level=3.5,
        temperature_range_min=18.0,
        temperature_range_max=45.0,
        description=(
            "Typical of desert and semi-arid regions (Gulf, Sahel). Very low organic matter, "
            "high pH, elevated salinity, and poor water retention. "
            "Requires frequent irrigation and heavy fertilisation."
        ),
        climate_zone="arid",
        created_at=NOW, updated_at=NOW,
    ),
    SoilProfile(
        id=MED_LOAM_ID,
        name="Mediterranean Loam",
        soil_type=SoilType.loam,
        ph_level=6.8,
        organic_matter_percent=2.5,
        drainage_rate=DrainageRate.good,
        water_retention=WaterRetention.medium,
        native_nitrogen=25.0,
        native_phosphorus=18.0,
        native_potassium=180.0,
        salinity_level=0.8,
        temperature_range_min=8.0,
        temperature_range_max=32.0,
        description=(
            "Well-balanced loam typical of Mediterranean basin. "
            "Good natural fertility and structure; ideal baseline for unmodified or lightly grafted cultivation."
        ),
        climate_zone="mediterranean",
        created_at=NOW, updated_at=NOW,
    ),
    SoilProfile(
        id=HEAVY_CLAY_ID,
        name="Heavy Clay",
        soil_type=SoilType.clay,
        ph_level=7.2,
        organic_matter_percent=3.5,
        drainage_rate=DrainageRate.poor,
        water_retention=WaterRetention.high,
        native_nitrogen=30.0,
        native_phosphorus=15.0,
        native_potassium=250.0,
        salinity_level=1.2,
        temperature_range_min=2.0,
        temperature_range_max=28.0,
        description=(
            "Dense clay typical of Northern European lowlands and river plains. "
            "High nutrient reserves but poor drainage causes waterlogging risk; "
            "raised beds or drainage systems strongly recommended."
        ),
        climate_zone="temperate",
        created_at=NOW, updated_at=NOW,
    ),
    SoilProfile(
        id=TROP_VOLCANIC_ID,
        name="Tropical Volcanic",
        soil_type=SoilType.loam,
        ph_level=5.8,
        organic_matter_percent=8.0,
        drainage_rate=DrainageRate.good,
        water_retention=WaterRetention.medium,
        native_nitrogen=45.0,
        native_phosphorus=12.0,
        native_potassium=320.0,
        salinity_level=0.3,
        temperature_range_min=20.0,
        temperature_range_max=35.0,
        description=(
            "Andisol derived from volcanic ash deposits (Hawaii, Indonesia, East Africa Rift). "
            "Very high organic matter and potassium; low available phosphorus due to P-fixation by allophane. "
            "Slightly acidic — benefits from lime application for tomato production."
        ),
        climate_zone="tropical",
        created_at=NOW, updated_at=NOW,
    ),
    SoilProfile(
        id=TEMP_ALLUVIAL_ID,
        name="Temperate Alluvial",
        soil_type=SoilType.silt,
        ph_level=6.5,
        organic_matter_percent=4.0,
        drainage_rate=DrainageRate.moderate,
        water_retention=WaterRetention.medium,
        native_nitrogen=35.0,
        native_phosphorus=22.0,
        native_potassium=200.0,
        salinity_level=0.5,
        temperature_range_min=5.0,
        temperature_range_max=26.0,
        description=(
            "Fertile alluvial silt deposited by river systems (Nile Delta, Po Valley, Rhine floodplain). "
            "High natural fertility and excellent structure make this the benchmark productive soil. "
            "Moderate irrigation needs."
        ),
        climate_zone="temperate",
        created_at=NOW, updated_at=NOW,
    ),
]


GRAFTS = [
    GraftCombination(
        id=uuid.UUID("33333333-3333-3333-3333-333333333301"),
        rootstock_id=BEAUFORT_ID,
        scion_id=ROMA_ID,
        compatibility_score=0.92,
        vigor_boost=1.25,
        yield_modifier=1.20,
        stress_tolerance_override={"drought_tolerance": 7, "salinity_tolerance": 7, "heat_tolerance": 7},
        notes=(
            "Classic commercial combination widely adopted in Dutch and Spanish greenhouse systems. "
            "Grafting onto Beaufort reliably improves early vigour, uniformity, and disease resistance."
        ),
        source_reference="Schwarz et al. (2010). Grafting as a tool to improve NaCl tolerance of vegetable crops. Sci. Hortic.",
        created_at=NOW, updated_at=NOW,
    ),
    GraftCombination(
        id=uuid.UUID("33333333-3333-3333-3333-333333333302"),
        rootstock_id=MAXIFORT_ID,
        scion_id=ROMA_ID,
        compatibility_score=0.95,
        vigor_boost=1.35,
        yield_modifier=1.25,
        stress_tolerance_override={"drought_tolerance": 8, "heat_tolerance": 8, "cold_tolerance": 5},
        notes=(
            "Maxifort's extra vigour is particularly beneficial for long-season Roma production "
            "in challenging environments. Plant density may need reduction vs. ungrafted crops."
        ),
        source_reference="Estañ et al. (2005). Grafted tomatoes for the production in saline and high-temperature soils. J. Food Agric. Environ.",
        created_at=NOW, updated_at=NOW,
    ),
    GraftCombination(
        id=uuid.UUID("33333333-3333-3333-3333-333333333303"),
        rootstock_id=BEAUFORT_ID,
        scion_id=CHERRY_ID,
        compatibility_score=0.88,
        vigor_boost=1.20,
        yield_modifier=1.15,
        stress_tolerance_override={"salinity_tolerance": 7, "drought_tolerance": 6},
        notes=(
            "Effective combination for warm-climate cherry tomato production under moderate disease pressure. "
            "Slightly lower compatibility than Roma × Beaufort but still commercially viable."
        ),
        source_reference="Rivero et al. (2003). The role of grafting in horticultural plants under stress conditions. J. Food Agric. Environ.",
        created_at=NOW, updated_at=NOW,
    ),
    GraftCombination(
        id=uuid.UUID("33333333-3333-3333-3333-333333333304"),
        rootstock_id=ARNOLD_ID,
        scion_id=CHERRY_ID,
        compatibility_score=0.85,
        vigor_boost=1.18,
        yield_modifier=1.10,
        stress_tolerance_override={"salinity_tolerance": 8, "drought_tolerance": 6},
        notes=(
            "Preferred combination for coastal and arid production where irrigation water EC exceeds 2.5 dS/m. "
            "Arnold's S. peruvianum genetics confer exceptional salt exclusion at the root level."
        ),
        source_reference="Colla et al. (2010). Grafting as tool for saline tolerance of vegetable crops. Sci. Hortic.",
        created_at=NOW, updated_at=NOW,
    ),
    GraftCombination(
        id=uuid.UUID("33333333-3333-3333-3333-333333333305"),
        rootstock_id=ARNOLD_ID,
        scion_id=BELL_PEPPER_ID,
        compatibility_score=0.72,
        vigor_boost=1.15,
        yield_modifier=1.10,
        stress_tolerance_override={"drought_tolerance": 6, "salinity_tolerance": 7, "heat_tolerance": 7},
        notes=(
            "Cross-genus inter-specific graft with moderate compatibility. "
            "Graft union success rate ~72%; requires careful temperature management during healing (26–28°C). "
            "Significant stress tolerance gains justify the technique in arid production systems."
        ),
        source_reference="Penella et al. (2014). Rootstock alleviates water stress in grafted pepper plants through its effect on plant biomass distribution. Sci. Hortic.",
        created_at=NOW, updated_at=NOW,
    ),
    GraftCombination(
        id=uuid.UUID("33333333-3333-3333-3333-333333333306"),
        rootstock_id=BEAUFORT_ID,
        scion_id=EGGPLANT_ID,
        compatibility_score=0.78,
        vigor_boost=1.22,
        yield_modifier=1.18,
        stress_tolerance_override={"heat_tolerance": 8, "drought_tolerance": 7, "salinity_tolerance": 6},
        notes=(
            "Solanaceous cross-graft showing good take rates in practice. "
            "Recommended for warm-climate eggplant where Fusarium and Verticillium wilt are endemic. "
            "Beaufort's deep root architecture significantly extends drought intervals."
        ),
        source_reference="Gisbert et al. (2011). Grafting solanaceous crops: A way to improve them under unfavorable soil conditions. Acta Hortic.",
        created_at=NOW, updated_at=NOW,
    ),
]


def seed():
    db = SessionLocal()
    try:
        existing = db.query(Plant).count()
        if existing > 0:
            print(f"Database already contains {existing} plant(s). Skipping seed.")
            return

        print("Seeding plants...")
        for plant in PLANTS:
            db.merge(plant)

        print("Seeding soil profiles...")
        for soil in SOILS:
            db.merge(soil)

        db.flush()

        print("Seeding graft combinations...")
        for graft in GRAFTS:
            db.merge(graft)

        db.commit()
        print(
            f"Done. Inserted {len(PLANTS)} plants, "
            f"{len(SOILS)} soil profiles, "
            f"{len(GRAFTS)} graft combinations."
        )
    except Exception as e:
        db.rollback()
        print(f"Seed failed: {e}", file=sys.stderr)
        raise
    finally:
        db.close()


if __name__ == "__main__":
    seed()
