from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import func as sql_func
from pydantic import BaseModel, Field
from datetime import date, datetime
from typing import Optional
from app.database import get_db
from app.models.plant_activation import PlantActivation, PlantOwnershipHistory, PlantCostRecord
from app.models.plant_lifecycle import PlantGrowthRecord, PlantTreatmentRecord, PlantHealthRecord, PlantHarvestRecord, PlantCareRecord, PlantCareSchedule
from app.models.farmer_support import PlantIssueReport, PlantWarrantyClaim
from app.models.passport import PlantPassport, PassportTimelineEvent
from app.models.farmer import FarmerProfile
from app.models.farm import Farm, FarmField
from app.services.auth import get_current_user
from app.models.user import User

router = APIRouter(prefix="/plant-activations", tags=["plant-activations"])


def _generate_activation_code(db: Session) -> str:
    year = date.today().year
    last = db.query(PlantActivation).order_by(PlantActivation.created_at.desc()).first()
    if last:
        try:
            seq = int(last.activation_id.split("-")[-1]) + 1
        except (ValueError, IndexError):
            seq = db.query(PlantActivation).count() + 1
    else:
        seq = db.query(PlantActivation).count() + 1
    return f"FAR-{year}-{seq:06d}"


class ActivationCreate(BaseModel):
    passport_id: str
    farmer_id: str
    farm_id: str
    field_id: Optional[str] = None
    purchase_date: Optional[date] = None
    activation_date: Optional[date] = None
    planting_date: Optional[date] = None
    initial_condition: Optional[str] = None
    initial_photo: Optional[str] = None
    gps_latitude: Optional[float] = None
    gps_longitude: Optional[float] = None
    notes: Optional[str] = None


class ActivationUpdate(BaseModel):
    farm_id: Optional[str] = None
    field_id: Optional[str] = None
    planting_date: Optional[date] = None
    initial_condition: Optional[str] = None
    initial_photo: Optional[str] = None
    gps_latitude: Optional[float] = None
    gps_longitude: Optional[float] = None
    notes: Optional[str] = None
    status: Optional[str] = None


class ActivationOut(BaseModel):
    id: str
    activation_id: str
    passport_id: str
    farmer_id: str
    farm_id: str
    field_id: Optional[str] = None
    purchase_date: Optional[date] = None
    activation_date: Optional[date] = None
    planting_date: Optional[date] = None
    initial_condition: Optional[str] = None
    initial_photo: Optional[str] = None
    gps_latitude: Optional[float] = None
    gps_longitude: Optional[float] = None
    notes: Optional[str] = None
    status: str
    created_at: datetime
    updated_at: Optional[datetime] = None
    passport_info: Optional[dict] = None
    farmer_info: Optional[dict] = None
    farm_info: Optional[dict] = None

    model_config = {"from_attributes": True}


class GrowthRecordCreate(BaseModel):
    record_date: Optional[date] = None
    plant_height_cm: Optional[float] = None
    stem_diameter_mm: Optional[float] = None
    canopy_size_cm: Optional[float] = None
    leaf_count: Optional[int] = None
    flower_count: Optional[int] = None
    fruit_count: Optional[int] = None
    health_score: Optional[float] = None
    growth_stage: Optional[str] = None
    general_health: Optional[str] = None
    photo_url: Optional[str] = None
    notes: Optional[str] = None


class GrowthRecordOut(BaseModel):
    id: str
    activation_id: str
    record_date: Optional[date] = None
    plant_height_cm: Optional[float] = None
    stem_diameter_mm: Optional[float] = None
    canopy_size_cm: Optional[float] = None
    leaf_count: Optional[int] = None
    flower_count: Optional[int] = None
    fruit_count: Optional[int] = None
    health_score: Optional[float] = None
    growth_stage: Optional[str] = None
    general_health: Optional[str] = None
    photo_url: Optional[str] = None
    notes: Optional[str] = None
    created_at: datetime

    model_config = {"from_attributes": True}


class TreatmentRecordCreate(BaseModel):
    treatment_date: Optional[date] = None
    treatment_type: str
    product_name: Optional[str] = None
    active_ingredient: Optional[str] = None
    dosage: Optional[str] = None
    quantity: Optional[float] = None
    unit: Optional[str] = None
    application_method: Optional[str] = None
    reason: Optional[str] = None
    cost: float = 0.0
    photo_url: Optional[str] = None
    notes: Optional[str] = None


class TreatmentRecordOut(BaseModel):
    id: str
    record_number: str
    activation_id: str
    treatment_date: Optional[date] = None
    treatment_type: str
    product_name: Optional[str] = None
    active_ingredient: Optional[str] = None
    dosage: Optional[str] = None
    quantity: Optional[float] = None
    unit: Optional[str] = None
    application_method: Optional[str] = None
    reason: Optional[str] = None
    cost: float
    photo_url: Optional[str] = None
    notes: Optional[str] = None
    created_at: datetime

    model_config = {"from_attributes": True}


class HealthRecordCreate(BaseModel):
    record_date: Optional[date] = None
    health_score: Optional[float] = None
    plant_height_cm: Optional[float] = None
    leaf_count: Optional[int] = None
    stem_thickness_mm: Optional[float] = None
    plant_color: Optional[str] = None
    root_status: Optional[str] = None
    moisture_level: Optional[float] = None
    mortality_rate: Optional[float] = None
    notes: Optional[str] = None


class HealthRecordOut(BaseModel):
    id: str
    activation_id: str
    record_date: Optional[date] = None
    health_score: Optional[float] = None
    plant_height_cm: Optional[float] = None
    leaf_count: Optional[int] = None
    stem_thickness_mm: Optional[float] = None
    plant_color: Optional[str] = None
    root_status: Optional[str] = None
    moisture_level: Optional[float] = None
    mortality_rate: Optional[float] = None
    notes: Optional[str] = None
    created_at: datetime

    model_config = {"from_attributes": True}


class HarvestRecordCreate(BaseModel):
    harvest_date: Optional[date] = None
    quantity: float = 0.0
    unit: Optional[str] = None
    grade: Optional[str] = None
    quality: Optional[str] = None
    selling_price: Optional[float] = None
    buyer: Optional[str] = None
    revenue: Optional[float] = None
    photo_url: Optional[str] = None
    notes: Optional[str] = None


class HarvestRecordOut(BaseModel):
    id: str
    harvest_number: str
    activation_id: str
    harvest_date: Optional[date] = None
    quantity: float
    unit: Optional[str] = None
    grade: Optional[str] = None
    quality: Optional[str] = None
    selling_price: Optional[float] = None
    buyer: Optional[str] = None
    revenue: Optional[float] = None
    photo_url: Optional[str] = None
    notes: Optional[str] = None
    created_at: datetime

    model_config = {"from_attributes": True}


class CostRecordCreate(BaseModel):
    cost_type: str
    amount: float
    description: Optional[str] = None
    date: Optional[date] = None
    notes: Optional[str] = None


class CostRecordOut(BaseModel):
    id: str
    activation_id: str
    cost_type: str
    amount: float
    description: Optional[str] = None
    date: Optional[date] = None
    notes: Optional[str] = None
    created_at: datetime

    model_config = {"from_attributes": True}


@router.get("", response_model=list[ActivationOut])
def list_activations(
    farmer_id: Optional[str] = None,
    status: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    q = db.query(PlantActivation)
    if farmer_id:
        q = q.filter(PlantActivation.farmer_id == farmer_id)
    if status:
        q = q.filter(PlantActivation.status == status)
    activations = q.order_by(PlantActivation.created_at.desc()).all()
    result = []
    for a in activations:
        out = ActivationOut.model_validate(a)
        passport = db.query(PlantPassport).filter(PlantPassport.id == a.passport_id).first()
        if passport:
            out.passport_info = {
                "passport_id": passport.passport_id,
                "plant_name": passport.plant_name,
                "variety_name": passport.variety_name,
                "qr_code": passport.qr_code,
            }
        farmer = db.query(FarmerProfile).filter(FarmerProfile.id == a.farmer_id).first()
        if farmer and farmer.customer:
            out.farmer_info = {
                "name": farmer.customer.name,
                "phone": farmer.customer.phone,
            }
        farm = db.query(Farm).filter(Farm.id == a.farm_id).first()
        if farm:
            out.farm_info = {"name": farm.name}
        result.append(out)
    return result


@router.post("", response_model=ActivationOut)
def create_activation(
    data: ActivationCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    passport = db.query(PlantPassport).filter(PlantPassport.id == data.passport_id).first()
    if not passport:
        raise HTTPException(status_code=404, detail="Passport not found")

    farmer = db.query(FarmerProfile).filter(FarmerProfile.id == data.farmer_id).first()
    if not farmer:
        raise HTTPException(status_code=404, detail="Farmer not found")

    farm = db.query(Farm).filter(Farm.id == data.farm_id).first()
    if not farm:
        raise HTTPException(status_code=404, detail="Farm not found")

    existing = db.query(PlantActivation).filter(PlantActivation.passport_id == data.passport_id).first()
    if existing:
        raise HTTPException(status_code=400, detail="This passport is already activated")

    activation = PlantActivation(
        activation_id=_generate_activation_code(db),
        passport_id=data.passport_id,
        farmer_id=data.farmer_id,
        farm_id=data.farm_id,
        field_id=data.field_id,
        purchase_date=data.purchase_date,
        activation_date=data.activation_date or date.today(),
        planting_date=data.planting_date,
        initial_condition=data.initial_condition,
        initial_photo=data.initial_photo,
        gps_latitude=data.gps_latitude,
        gps_longitude=data.gps_longitude,
        notes=data.notes,
        status="activated",
    )
    db.add(activation)

    ownership = PlantOwnershipHistory(
        passport_id=data.passport_id,
        from_owner_type="nursery",
        to_owner_type="farmer",
        to_owner_id=data.farmer_id,
        transfer_date=date.today(),
        transfer_reason="Sale",
        authorized_by=current_user.id,
    )
    db.add(ownership)

    passport.owner_id = farmer.customer_id
    passport.activation_status = "activated"

    timeline = PassportTimelineEvent(
        passport_id=data.passport_id,
        event_date=date.today(),
        event_type="activation",
        event_title="Plant activated by farmer",
        event_details=f"Plant activated by {farmer.customer.name if farmer.customer else 'farmer'}",
        icon="👨‍🌾",
        recorded_by=current_user.id,
    )
    db.add(timeline)

    db.commit()
    db.refresh(activation)

    out = ActivationOut.model_validate(activation)
    out.passport_info = {
        "passport_id": passport.passport_id,
        "plant_name": passport.plant_name,
        "variety_name": passport.variety_name,
    }
    return out


# Today's Tasks (all due care tasks for a farmer)
@router.get("/today-tasks")
def get_today_tasks(
    farmer_id: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    from datetime import timedelta
    today = date.today()

    q = db.query(PlantCareSchedule).join(PlantActivation).filter(
        PlantCareSchedule.is_active == True,
        PlantCareSchedule.next_due_date <= today,
    )
    if farmer_id:
        q = q.filter(PlantActivation.farmer_id == farmer_id)

    due_schedules = q.order_by(PlantCareSchedule.next_due_date).all()

    tasks = []
    for s in due_schedules:
        activation = db.query(PlantActivation).filter(PlantActivation.id == s.activation_id).first()
        passport = db.query(PlantPassport).filter(PlantPassport.id == activation.passport_id).first() if activation else None
        farm = db.query(Farm).filter(Farm.id == activation.farm_id).first() if activation else None
        overdue = (today - s.next_due_date).days if s.next_due_date else 0

        tasks.append({
            "id": s.id,
            "activation_id": s.activation_id,
            "care_type": s.care_type,
            "frequency_days": s.frequency_days,
            "next_due_date": str(s.next_due_date),
            "overdue_days": overdue,
            "is_overdue": overdue > 0,
            "notes": s.notes,
            "plant_name": passport.plant_name if passport else None,
            "passport_id": passport.passport_id if passport else None,
            "farm_name": farm.name if farm else None,
        })

    return {"tasks": tasks, "total": len(tasks), "overdue": sum(1 for t in tasks if t["is_overdue"])}


@router.get("/{activation_id}", response_model=ActivationOut)
def get_activation(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    out = ActivationOut.model_validate(activation)
    passport = db.query(PlantPassport).filter(PlantPassport.id == activation.passport_id).first()
    if passport:
        out.passport_info = {
            "passport_id": passport.passport_id,
            "plant_name": passport.plant_name,
            "variety_name": passport.variety_name,
            "scientific_name": passport.scientific_name,
            "qr_code": passport.qr_code,
            "health_status": passport.health_status,
        }
    farmer = db.query(FarmerProfile).filter(FarmerProfile.id == activation.farmer_id).first()
    if farmer and farmer.customer:
        out.farmer_info = {
            "name": farmer.customer.name,
            "phone": farmer.customer.phone,
            "farm_name": farmer.farm_name,
        }
    farm = db.query(Farm).filter(Farm.id == activation.farm_id).first()
    if farm:
        out.farm_info = {"name": farm.name, "area": farm.area}
    return out


@router.put("/{activation_id}", response_model=ActivationOut)
def update_activation(
    activation_id: str,
    data: ActivationUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    update_data = data.model_dump(exclude_unset=True)
    for key, value in update_data.items():
        setattr(activation, key, value)
    db.commit()
    db.refresh(activation)

    out = ActivationOut.model_validate(activation)
    passport = db.query(PlantPassport).filter(PlantPassport.id == activation.passport_id).first()
    if passport:
        out.passport_info = {
            "passport_id": passport.passport_id,
            "plant_name": passport.plant_name,
        }
    return out


class DeactivateCreate(BaseModel):
    reason: Optional[str] = None
    deactivated_at: Optional[date] = None


@router.post("/{activation_id}/deactivate", response_model=ActivationOut)
def deactivate_plant(
    activation_id: str,
    data: DeactivateCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")
    if activation.status == "deactivated":
        raise HTTPException(status_code=400, detail="Already deactivated")

    activation.status = "deactivated"

    passport = db.query(PlantPassport).filter(PlantPassport.id == activation.passport_id).first()
    if passport:
        passport.activation_status = "deactivated"

    ownership = PlantOwnershipHistory(
        passport_id=activation.passport_id,
        activation_id=activation_id,
        from_owner_type="farmer",
        from_owner_id=activation.farmer_id,
        to_owner_type="nursery",
        transfer_date=data.deactivated_at or date.today(),
        transfer_reason=data.reason or "Deactivated",
        authorized_by=current_user.id,
    )
    db.add(ownership)

    timeline = PassportTimelineEvent(
        passport_id=activation.passport_id,
        event_date=date.today(),
        event_type="deactivation",
        event_title="Plant deactivated",
        event_details=data.reason or "Plant deactivated by farmer",
        icon="🚫",
        recorded_by=current_user.id,
    )
    db.add(timeline)

    db.commit()
    db.refresh(activation)

    out = ActivationOut.model_validate(activation)
    if passport:
        out.passport_info = {
            "passport_id": passport.passport_id,
            "plant_name": passport.plant_name,
        }
    return out


@router.get("/{activation_id}/timeline")
def get_activation_timeline(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    passport = db.query(PlantPassport).filter(PlantPassport.id == activation.passport_id).first()
    nursery_events = []
    if passport:
        events = db.query(PassportTimelineEvent).filter(
            PassportTimelineEvent.passport_id == passport.id
        ).order_by(PassportTimelineEvent.event_date).all()
        nursery_events = [
            {
                "date": str(e.event_date),
                "type": e.event_type,
                "title": e.event_title,
                "details": e.event_details,
                "icon": e.icon,
            }
            for e in events
        ]

    growth_events = db.query(PlantGrowthRecord).filter(
        PlantGrowthRecord.activation_id == activation_id
    ).order_by(PlantGrowthRecord.record_date).all()
    treatment_events = db.query(PlantTreatmentRecord).filter(
        PlantTreatmentRecord.activation_id == activation_id
    ).order_by(PlantTreatmentRecord.treatment_date).all()
    harvest_events = db.query(PlantHarvestRecord).filter(
        PlantHarvestRecord.activation_id == activation_id
    ).order_by(PlantHarvestRecord.harvest_date).all()

    farmer_events = []
    for g in growth_events:
        farmer_events.append({
            "date": str(g.record_date),
            "type": "growth",
            "title": f"Growth recorded - {g.growth_stage or 'N/A'}",
            "details": f"Height: {g.plant_height_cm}cm, Health: {g.health_score}%",
            "icon": "🌿",
        })
    for t in treatment_events:
        farmer_events.append({
            "date": str(t.treatment_date),
            "type": "treatment",
            "title": f"Treatment - {t.treatment_type}",
            "details": t.product_name or "",
            "icon": "💊",
        })
    for h in harvest_events:
        farmer_events.append({
            "date": str(h.harvest_date),
            "type": "harvest",
            "title": f"Harvest - {h.quantity} {h.unit or ''}",
            "details": f"Revenue: ৳{h.revenue or 0}",
            "icon": "🧺",
        })

    farmer_events.sort(key=lambda x: x["date"])

    return {
        "nursery_events": nursery_events,
        "farmer_events": farmer_events,
        "all_events": nursery_events + farmer_events,
    }


@router.get("/{activation_id}/passport")
def get_enhanced_passport(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    passport = db.query(PlantPassport).filter(PlantPassport.id == activation.passport_id).first()
    if not passport:
        raise HTTPException(status_code=404, detail="Passport not found")

    farmer = db.query(FarmerProfile).filter(FarmerProfile.id == activation.farmer_id).first()
    farm = db.query(Farm).filter(Farm.id == activation.farm_id).first()
    field = db.query(FarmField).filter(FarmField.id == activation.field_id).first() if activation.field_id else None

    growth_records = db.query(PlantGrowthRecord).filter(
        PlantGrowthRecord.activation_id == activation_id
    ).order_by(PlantGrowthRecord.record_date.desc()).limit(5).all()

    treatment_records = db.query(PlantTreatmentRecord).filter(
        PlantTreatmentRecord.activation_id == activation_id
    ).order_by(PlantTreatmentRecord.treatment_date.desc()).limit(5).all()

    harvest_records = db.query(PlantHarvestRecord).filter(
        PlantHarvestRecord.activation_id == activation_id
    ).order_by(PlantHarvestRecord.harvest_date.desc()).limit(5).all()

    total_cost = db.query(sql_func.sum(PlantCostRecord.amount)).filter(
        PlantCostRecord.activation_id == activation_id
    ).scalar() or 0

    total_revenue = db.query(sql_func.sum(PlantHarvestRecord.revenue)).filter(
        PlantHarvestRecord.activation_id == activation_id,
        PlantHarvestRecord.revenue.isnot(None)
    ).scalar() or 0

    return {
        "passport": {
            "passport_id": passport.passport_id,
            "plant_name": passport.plant_name,
            "scientific_name": passport.scientific_name,
            "variety_name": passport.variety_name,
            "category_name": passport.category_name,
            "health_status": passport.health_status,
            "health_score": passport.health_score,
            "current_growth_stage": passport.current_growth_stage,
            "qr_code": passport.qr_code,
        },
        "activation": {
            "activation_id": activation.activation_id,
            "status": activation.status,
            "planting_date": str(activation.planting_date) if activation.planting_date else None,
            "gps_latitude": activation.gps_latitude,
            "gps_longitude": activation.gps_longitude,
        },
        "farmer": {
            "name": farmer.customer.name if farmer and farmer.customer else None,
            "phone": farmer.customer.phone if farmer and farmer.customer else None,
            "farm_name": farmer.farm_name if farmer else None,
        },
        "farm": {
            "name": farm.name if farm else None,
            "area": farm.area if farm else None,
        },
        "field": {
            "name": field.name if field else None,
            "area": field.area if field else None,
        } if field else None,
        "growth_records": [GrowthRecordOut.model_validate(g).model_dump() for g in growth_records],
        "treatment_records": [TreatmentRecordOut.model_validate(t).model_dump() for t in treatment_records],
        "harvest_records": [HarvestRecordOut.model_validate(h).model_dump() for h in harvest_records],
        "economics": {
            "total_cost": total_cost,
            "total_revenue": total_revenue,
            "profit": total_revenue - total_cost,
        },
    }


# Growth Records
@router.get("/{activation_id}/growth", response_model=list[GrowthRecordOut])
def list_growth_records(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = db.query(PlantGrowthRecord).filter(
        PlantGrowthRecord.activation_id == activation_id
    ).order_by(PlantGrowthRecord.record_date.desc()).all()
    return [GrowthRecordOut.model_validate(r) for r in records]


@router.post("/{activation_id}/growth", response_model=GrowthRecordOut)
def create_growth_record(
    activation_id: str,
    data: GrowthRecordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    record = PlantGrowthRecord(
        activation_id=activation_id,
        record_date=data.record_date or date.today(),
        plant_height_cm=data.plant_height_cm,
        stem_diameter_mm=data.stem_diameter_mm,
        canopy_size_cm=data.canopy_size_cm,
        leaf_count=data.leaf_count,
        flower_count=data.flower_count,
        fruit_count=data.fruit_count,
        health_score=data.health_score,
        growth_stage=data.growth_stage,
        general_health=data.general_health,
        photo_url=data.photo_url,
        notes=data.notes,
        recorded_by=current_user.id,
    )
    db.add(record)

    if data.growth_stage:
        activation.status = data.growth_stage

    db.commit()
    db.refresh(record)
    return GrowthRecordOut.model_validate(record)


# Treatment Records
@router.get("/{activation_id}/treatments", response_model=list[TreatmentRecordOut])
def list_treatment_records(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = db.query(PlantTreatmentRecord).filter(
        PlantTreatmentRecord.activation_id == activation_id
    ).order_by(PlantTreatmentRecord.treatment_date.desc()).all()
    return [TreatmentRecordOut.model_validate(r) for r in records]


@router.post("/{activation_id}/treatments", response_model=TreatmentRecordOut)
def create_treatment_record(
    activation_id: str,
    data: TreatmentRecordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    year = date.today().year
    last = db.query(PlantTreatmentRecord).order_by(PlantTreatmentRecord.created_at.desc()).first()
    if last:
        try:
            seq = int(last.record_number.split("-")[-1]) + 1
        except (ValueError, IndexError):
            seq = db.query(PlantTreatmentRecord).count() + 1
    else:
        seq = db.query(PlantTreatmentRecord).count() + 1

    record = PlantTreatmentRecord(
        record_number=f"PTR-{year}-{seq:06d}",
        activation_id=activation_id,
        treatment_date=data.treatment_date or date.today(),
        treatment_type=data.treatment_type,
        product_name=data.product_name,
        active_ingredient=data.active_ingredient,
        dosage=data.dosage,
        quantity=data.quantity,
        unit=data.unit,
        application_method=data.application_method,
        reason=data.reason,
        cost=data.cost,
        photo_url=data.photo_url,
        notes=data.notes,
        recorded_by=current_user.id,
    )
    db.add(record)
    db.commit()
    db.refresh(record)
    return TreatmentRecordOut.model_validate(record)


# Health Records
@router.get("/{activation_id}/health", response_model=list[HealthRecordOut])
def list_health_records(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = db.query(PlantHealthRecord).filter(
        PlantHealthRecord.activation_id == activation_id
    ).order_by(PlantHealthRecord.record_date.desc()).all()
    return [HealthRecordOut.model_validate(r) for r in records]


@router.post("/{activation_id}/health", response_model=HealthRecordOut)
def create_health_record(
    activation_id: str,
    data: HealthRecordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    record = PlantHealthRecord(
        activation_id=activation_id,
        record_date=data.record_date or date.today(),
        health_score=data.health_score,
        plant_height_cm=data.plant_height_cm,
        leaf_count=data.leaf_count,
        stem_thickness_mm=data.stem_thickness_mm,
        plant_color=data.plant_color,
        root_status=data.root_status,
        moisture_level=data.moisture_level,
        mortality_rate=data.mortality_rate,
        notes=data.notes,
        recorded_by=current_user.id,
    )
    db.add(record)
    db.commit()
    db.refresh(record)
    return HealthRecordOut.model_validate(record)


# Harvest Records
@router.get("/{activation_id}/harvests", response_model=list[HarvestRecordOut])
def list_harvest_records(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = db.query(PlantHarvestRecord).filter(
        PlantHarvestRecord.activation_id == activation_id
    ).order_by(PlantHarvestRecord.harvest_date.desc()).all()
    return [HarvestRecordOut.model_validate(r) for r in records]


@router.get("/{activation_id}/harvest", response_model=list[HarvestRecordOut])
def list_harvest_records_alias(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = db.query(PlantHarvestRecord).filter(
        PlantHarvestRecord.activation_id == activation_id
    ).order_by(PlantHarvestRecord.harvest_date.desc()).all()
    return [HarvestRecordOut.model_validate(r) for r in records]


@router.post("/{activation_id}/harvests", response_model=HarvestRecordOut)
def create_harvest_record(
    activation_id: str,
    data: HarvestRecordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    year = date.today().year
    last = db.query(PlantHarvestRecord).order_by(PlantHarvestRecord.created_at.desc()).first()
    if last:
        try:
            seq = int(last.harvest_number.split("-")[-1]) + 1
        except (ValueError, IndexError):
            seq = db.query(PlantHarvestRecord).count() + 1
    else:
        seq = db.query(PlantHarvestRecord).count() + 1

    record = PlantHarvestRecord(
        harvest_number=f"HRV-{year}-{seq:06d}",
        activation_id=activation_id,
        harvest_date=data.harvest_date or date.today(),
        quantity=data.quantity,
        unit=data.unit,
        grade=data.grade,
        quality=data.quality,
        selling_price=data.selling_price,
        buyer=data.buyer,
        revenue=data.revenue,
        photo_url=data.photo_url,
        notes=data.notes,
        recorded_by=current_user.id,
    )
    db.add(record)
    db.commit()
    db.refresh(record)
    return HarvestRecordOut.model_validate(record)


@router.post("/{activation_id}/harvest", response_model=HarvestRecordOut)
def create_harvest_record_alias(
    activation_id: str,
    data: HarvestRecordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    return create_harvest_record(activation_id, data, db, current_user)


# Care Records
class CareRecordCreate(BaseModel):
    care_type: str
    care_date: Optional[date] = None
    quantity: Optional[float] = None
    unit: Optional[str] = None
    method: Optional[str] = None
    cost: float = 0.0
    notes: Optional[str] = None


class CareRecordOut(BaseModel):
    id: str
    activation_id: str
    care_type: str
    care_date: Optional[date] = None
    quantity: Optional[float] = None
    unit: Optional[str] = None
    method: Optional[str] = None
    cost: float
    notes: Optional[str] = None
    created_at: datetime

    model_config = {"from_attributes": True}


@router.get("/{activation_id}/care", response_model=list[CareRecordOut])
def list_care_records(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = db.query(PlantCareRecord).filter(
        PlantCareRecord.activation_id == activation_id
    ).order_by(PlantCareRecord.care_date.desc()).all()
    return [CareRecordOut.model_validate(r) for r in records]


@router.post("/{activation_id}/care", response_model=CareRecordOut)
def create_care_record(
    activation_id: str,
    data: CareRecordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    record = PlantCareRecord(
        activation_id=activation_id,
        care_type=data.care_type,
        care_date=data.care_date or date.today(),
        quantity=data.quantity,
        unit=data.unit,
        method=data.method,
        cost=data.cost,
        notes=data.notes,
        recorded_by=current_user.id,
    )
    db.add(record)
    db.commit()
    db.refresh(record)
    return CareRecordOut.model_validate(record)


# Cost Records
@router.get("/{activation_id}/costs")
def list_cost_records(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = db.query(PlantCostRecord).filter(
        PlantCostRecord.activation_id == activation_id
    ).order_by(PlantCostRecord.created_at.desc()).all()
    return [
        {
            "id": r.id,
            "activation_id": r.activation_id,
            "cost_type": r.cost_type,
            "amount": r.amount,
            "description": r.description,
            "date": str(r.date) if r.date else None,
            "notes": r.notes,
            "created_at": r.created_at.isoformat() if r.created_at else None,
        }
        for r in records
    ]


@router.post("/{activation_id}/costs")
def create_cost_record(
    activation_id: str,
    data: CostRecordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    record = PlantCostRecord(
        activation_id=activation_id,
        cost_type=data.cost_type,
        amount=data.amount,
        description=data.description,
        date=data.date or date.today(),
        notes=data.notes,
    )
    db.add(record)
    db.commit()
    db.refresh(record)
    return {
        "id": record.id,
        "activation_id": record.activation_id,
        "cost_type": record.cost_type,
        "amount": record.amount,
        "description": record.description,
        "date": str(record.date) if record.date else None,
        "notes": record.notes,
        "created_at": record.created_at.isoformat() if record.created_at else None,
    }


@router.get("/{activation_id}/roi")
def get_roi(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    costs = db.query(PlantCostRecord).filter(PlantCostRecord.activation_id == activation_id).all()
    harvests = db.query(PlantHarvestRecord).filter(PlantHarvestRecord.activation_id == activation_id).all()

    cost_breakdown = {}
    total_cost = 0
    for c in costs:
        cost_breakdown[c.cost_type] = cost_breakdown.get(c.cost_type, 0) + c.amount
        total_cost += c.amount

    total_revenue = sum(h.revenue or 0 for h in harvests)

    return {
        "total_cost": total_cost,
        "total_revenue": total_revenue,
        "profit": total_revenue - total_cost,
        "roi_percentage": ((total_revenue - total_cost) / total_cost * 100) if total_cost > 0 else 0,
        "cost_breakdown": cost_breakdown,
        "harvest_count": len(harvests),
    }


# Care Schedules
class CareScheduleCreate(BaseModel):
    care_type: str
    frequency_days: int = 1
    next_due_date: Optional[date] = None
    reminder_time: Optional[str] = None
    notes: Optional[str] = None


class CareScheduleOut(BaseModel):
    id: str
    activation_id: str
    care_type: str
    frequency_days: int
    next_due_date: Optional[date] = None
    last_completed: Optional[date] = None
    is_active: bool
    reminder_time: Optional[str] = None
    notes: Optional[str] = None
    created_at: datetime

    model_config = {"from_attributes": True}


@router.get("/{activation_id}/schedules", response_model=list[CareScheduleOut])
def list_care_schedules(
    activation_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = db.query(PlantCareSchedule).filter(
        PlantCareSchedule.activation_id == activation_id,
        PlantCareSchedule.is_active == True,
    ).order_by(PlantCareSchedule.next_due_date).all()
    return [CareScheduleOut.model_validate(r) for r in records]


@router.post("/{activation_id}/schedules", response_model=CareScheduleOut)
def create_care_schedule(
    activation_id: str,
    data: CareScheduleCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    activation = db.query(PlantActivation).filter(PlantActivation.id == activation_id).first()
    if not activation:
        raise HTTPException(status_code=404, detail="Activation not found")

    schedule = PlantCareSchedule(
        activation_id=activation_id,
        care_type=data.care_type,
        frequency_days=data.frequency_days,
        next_due_date=data.next_due_date or date.today(),
        reminder_time=data.reminder_time,
        notes=data.notes,
    )
    db.add(schedule)
    db.commit()
    db.refresh(schedule)
    return CareScheduleOut.model_validate(schedule)


@router.post("/{activation_id}/schedules/{schedule_id}/complete", response_model=CareScheduleOut)
def complete_care_schedule(
    activation_id: str,
    schedule_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    schedule = db.query(PlantCareSchedule).filter(
        PlantCareSchedule.id == schedule_id,
        PlantCareSchedule.activation_id == activation_id,
    ).first()
    if not schedule:
        raise HTTPException(status_code=404, detail="Schedule not found")

    from datetime import timedelta
    schedule.last_completed = date.today()
    schedule.next_due_date = date.today() + timedelta(days=schedule.frequency_days)

    care_record = PlantCareRecord(
        activation_id=activation_id,
        care_type=schedule.care_type,
        care_date=date.today(),
        notes=f"Completed per schedule",
        recorded_by=current_user.id,
    )
    db.add(care_record)

    timeline = PassportTimelineEvent(
        passport_id=db.query(PlantActivation).filter(PlantActivation.id == activation_id).first().passport_id,
        event_date=date.today(),
        event_type="care",
        event_title=f"{schedule.care_type.capitalize()} completed",
        event_details=schedule.notes or "",
        icon="💧" if schedule.care_type == "watering" else "🧪",
        recorded_by=current_user.id,
    )
    db.add(timeline)

    db.commit()
    db.refresh(schedule)
    return CareScheduleOut.model_validate(schedule)


@router.delete("/{activation_id}/schedules/{schedule_id}")
def delete_care_schedule(
    activation_id: str,
    schedule_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    schedule = db.query(PlantCareSchedule).filter(
        PlantCareSchedule.id == schedule_id,
        PlantCareSchedule.activation_id == activation_id,
    ).first()
    if not schedule:
        raise HTTPException(status_code=404, detail="Schedule not found")
    schedule.is_active = False
    db.commit()
    return {"ok": True}



