"""Farmer lifecycle analytics endpoints."""
from __future__ import annotations
from datetime import date, timedelta
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import func as sql_func
from pydantic import BaseModel
from app.database import get_db
from app.models.plant_activation import PlantActivation, PlantCostRecord
from app.models.plant_lifecycle import PlantGrowthRecord, PlantHarvestRecord, PlantCareSchedule
from app.models.passport import PlantPassport
from app.models.farmer import FarmerProfile
from app.models.farm import Farm
from app.models.customer import Customer
from app.services.auth import get_current_user
from app.models.user import User

router = APIRouter(prefix="/analytics", tags=["analytics"])


@router.get("/farmer/{farmer_id}/overview")
def farmer_overview(farmer_id: str, db: Session = Depends(get_db), _=Depends(get_current_user)):
    activations = db.query(PlantActivation).filter(PlantActivation.farmer_id == farmer_id).all()
    total = len(activations)
    active = sum(1 for a in activations if a.status in ("activated", "planted", "growing"))
    harvested = sum(1 for a in activations if a.status == "harvested")
    deactivated = sum(1 for a in activations if a.status == "deactivated")

    farms = db.query(Farm).filter(Farm.farmer_id == farmer_id).count()

    total_cost = db.query(sql_func.coalesce(sql_func.sum(PlantCostRecord.amount), 0)).join(
        PlantActivation
    ).filter(PlantActivation.farmer_id == farmer_id).scalar() or 0

    total_revenue = db.query(sql_func.coalesce(sql_func.sum(PlantHarvestRecord.revenue), 0)).join(
        PlantActivation
    ).filter(PlantActivation.farmer_id == farmer_id).scalar() or 0

    total_harvest_kg = db.query(sql_func.coalesce(sql_func.sum(PlantHarvestRecord.quantity), 0)).join(
        PlantActivation
    ).filter(PlantActivation.farmer_id == farmer_id).scalar() or 0

    return {
        "total_plants": total,
        "active_plants": active,
        "harvested_plants": harvested,
        "deactivated_plants": deactivated,
        "survival_rate": round((active / total * 100) if total > 0 else 0, 1),
        "total_farms": farms,
        "total_cost": float(total_cost),
        "total_revenue": float(total_revenue),
        "profit": float(total_revenue - total_cost),
        "roi_percentage": round(((total_revenue - total_cost) / total_cost * 100) if total_cost > 0 else 0, 1),
        "total_harvest_kg": float(total_harvest_kg),
    }


@router.get("/farmer/{farmer_id}/harvest-timeline")
def harvest_timeline(farmer_id: str, days: int = 90, db: Session = Depends(get_db), _=Depends(get_current_user)):
    cutoff = date.today() - timedelta(days=days)
    harvests = db.query(PlantHarvestRecord).join(PlantActivation).filter(
        PlantActivation.farmer_id == farmer_id,
        PlantHarvestRecord.harvest_date >= cutoff,
    ).order_by(PlantHarvestRecord.harvest_date).all()

    daily = {}
    for h in harvests:
        key = str(h.harvest_date) if h.harvest_date else str(cutoff)
        if key not in daily:
            daily[key] = {"date": key, "quantity": 0, "revenue": 0, "count": 0}
        daily[key]["quantity"] += h.quantity or 0
        daily[key]["revenue"] += h.revenue or 0
        daily[key]["count"] += 1

    return list(daily.values())


@router.get("/farmer/{farmer_id}/cost-breakdown")
def cost_breakdown(farmer_id: str, db: Session = Depends(get_db), _=Depends(get_current_user)):
    costs = db.query(PlantCostRecord).join(PlantActivation).filter(
        PlantActivation.farmer_id == farmer_id,
    ).all()

    breakdown = {}
    monthly = {}
    for c in costs:
        breakdown[c.cost_type] = breakdown.get(c.cost_type, 0) + c.amount
        month_key = c.date.strftime("%Y-%m") if c.date else "unknown"
        if month_key not in monthly:
            monthly[month_key] = {"month": month_key, "total": 0}
        monthly[month_key]["total"] += c.amount

    return {
        "by_type": [{"type": k, "amount": v} for k, v in sorted(breakdown.items(), key=lambda x: -x[1])],
        "monthly": sorted(monthly.values(), key=lambda x: x["month"]),
    }


@router.get("/farmer/{farmer_id}/growth-summary")
def growth_summary(farmer_id: str, db: Session = Depends(get_db), _=Depends(get_current_user)):
    records = db.query(PlantGrowthRecord).join(PlantActivation).filter(
        PlantActivation.farmer_id == farmer_id,
    ).order_by(PlantGrowthRecord.record_date).all()

    by_stage = {}
    for r in records:
        stage = r.growth_stage or "unknown"
        if stage not in by_stage:
            by_stage[stage] = {"stage": stage, "count": 0, "avg_height": 0, "avg_health": 0, "total_height": 0, "total_health": 0}
        by_stage[stage]["count"] += 1
        by_stage[stage]["total_height"] += r.plant_height_cm or 0
        by_stage[stage]["total_health"] += r.health_score or 0

    for stage in by_stage.values():
        stage["avg_height"] = round(stage["total_height"] / stage["count"], 1) if stage["count"] > 0 else 0
        stage["avg_health"] = round(stage["total_health"] / stage["count"], 1) if stage["count"] > 0 else 0

    timeline = []
    for r in records[-20:]:
        timeline.append({
            "date": str(r.record_date) if r.record_date else None,
            "stage": r.growth_stage,
            "height": r.plant_height_cm,
            "health": r.health_score,
            "leaves": r.leaf_count,
        })

    return {"by_stage": list(by_stage.values()), "timeline": timeline}


@router.get("/farmer/{farmer_id}/activation-stats")
def activation_stats(farmer_id: str, db: Session = Depends(get_db), _=Depends(get_current_user)):
    activations = db.query(PlantActivation).filter(
        PlantActivation.farmer_id == farmer_id,
    ).order_by(PlantActivation.created_at).all()

    monthly = {}
    for a in activations:
        month_key = a.created_at.strftime("%Y-%m") if a.created_at else "unknown"
        if month_key not in monthly:
            monthly[month_key] = {"month": month_key, "count": 0, "statuses": {}}
        monthly[month_key]["count"] += 1
        monthly[month_key]["statuses"][a.status] = monthly[month_key]["statuses"].get(a.status, 0) + 1

    return {"monthly": list(monthly.values()), "total": len(activations)}


@router.get("/nursery/overview")
def nursery_overview(db: Session = Depends(get_db), _=Depends(get_current_user)):
    total_farmers = db.query(sql_func.count(FarmerProfile.id)).scalar() or 0
    total_activations = db.query(sql_func.count(PlantActivation.id)).scalar() or 0
    active = db.query(sql_func.count(PlantActivation.id)).filter(
        PlantActivation.status.in_(["activated", "planted", "growing"])
    ).scalar() or 0
    total_cost = db.query(sql_func.coalesce(sql_func.sum(PlantCostRecord.amount), 0)).scalar() or 0
    total_revenue = db.query(sql_func.coalesce(sql_func.sum(PlantHarvestRecord.revenue), 0)).scalar() or 0
    total_harvest = db.query(sql_func.coalesce(sql_func.sum(PlantHarvestRecord.quantity), 0)).scalar() or 0
    total_farms = db.query(sql_func.count(Farm.id)).scalar() or 0

    status_counts = db.query(
        PlantActivation.status, sql_func.count(PlantActivation.id)
    ).group_by(PlantActivation.status).all()

    return {
        "total_farmers": total_farmers,
        "total_plants": total_activations,
        "active_plants": active,
        "survival_rate": round((active / total_activations * 100) if total_activations > 0 else 0, 1),
        "total_farms": total_farms,
        "total_cost": float(total_cost),
        "total_revenue": float(total_revenue),
        "profit": float(total_revenue - total_cost),
        "total_harvest_kg": float(total_harvest),
        "status_distribution": [{"status": s, "count": c} for s, c in status_counts],
    }
