"""
Beneficiary and Aid Assistance Models for NGO Foundation.
Provides digital profiling of beneficiaries (Labharthi), vulnerability classification,
and tracking of all relief, financial, medical, and material aid assistance distributed.
All code contains proper English comments for clarity and maintenance.
"""

from datetime import date, datetime, timezone
from app.extensions import db


class Beneficiary(db.Model):
    """
    Core profile of an individual or family beneficiary receiving aid from the NGO.
    """
    __tablename__ = 'beneficiaries'

    id = db.Column(db.Integer, primary_key=True)
    beneficiary_code = db.Column(db.String(32), unique=True, nullable=False, index=True)
    full_name = db.Column(db.String(120), nullable=False, index=True)
    gender = db.Column(db.String(20), nullable=False, default='Other')  # Male, Female, Other
    age = db.Column(db.Integer, nullable=True)
    contact_phone = db.Column(db.String(30), nullable=True, index=True)
    contact_email = db.Column(db.String(120), nullable=True)
    
    # Category / Vulnerability classification as per NGO statutory welfare schemes
    category = db.Column(db.String(50), nullable=False, default='General BPL')
    # Options: Widow, Divyang / Disabled, Student / Child, BPL Family, Patient / Medical, Senior Citizen, Orphan, Disaster Relief, General BPL
    
    id_proof_type = db.Column(db.String(50), nullable=True)  # Aadhaar, Ration Card, Voter ID, Disability Cert, None
    id_proof_number = db.Column(db.String(50), nullable=True)  # Stored masked or reference
    family_members_count = db.Column(db.Integer, nullable=False, default=1)
    monthly_income = db.Column(db.Float, nullable=False, default=0.0)
    
    # Location and Residence
    address_line = db.Column(db.String(255), nullable=True)
    city_or_district = db.Column(db.String(100), nullable=True, index=True)
    state = db.Column(db.String(100), nullable=False, default='Delhi')
    pincode = db.Column(db.String(20), nullable=True)
    
    status = db.Column(db.String(30), nullable=False, default='Active')  # Active, Inactive, Completed
    notes = db.Column(db.Text, nullable=True)

    created_at = db.Column(db.DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc))
    updated_at = db.Column(db.DateTime(timezone=True), nullable=True, onupdate=lambda: datetime.now(timezone.utc))

    # Relationship to all aid/assistance packages received over time
    aids = db.relationship('BeneficiaryAid', backref='beneficiary', cascade='all, delete-orphan', lazy='dynamic', order_by='BeneficiaryAid.aid_date.desc()')

    @property
    def total_aid_value(self) -> float:
        """Returns total cumulative economic or cash value of all aid received."""
        return sum(aid.amount_or_value for aid in self.aids)

    @property
    def aid_count(self) -> int:
        """Returns count of aid distribution events for this beneficiary."""
        return self.aids.count()

    def __repr__(self):
        return f"<Beneficiary {self.beneficiary_code} - {self.full_name}>"


class BeneficiaryAid(db.Model):
    """
    Record of a specific relief or welfare aid distributed to a beneficiary.
    Tracks aid type, monetary value, date, items, and distributing personnel.
    """
    __tablename__ = 'beneficiary_aids'

    id = db.Column(db.Integer, primary_key=True)
    beneficiary_id = db.Column(db.Integer, db.ForeignKey('beneficiaries.id'), nullable=False, index=True)
    
    aid_type = db.Column(db.String(80), nullable=False)
    # Types: Financial / Cash Support, Ration Kit, Medical Support / Medicines, Blanket / Warm Clothes, Wheelchair / Mobility Aid, Educational Books & Kit, Cooked Food / Nutrition, Emergency Disaster Relief, Other
    
    amount_or_value = db.Column(db.Float, nullable=False, default=0.0)
    aid_date = db.Column(db.Date, nullable=False, default=date.today)
    item_description = db.Column(db.Text, nullable=True)
    reference_no = db.Column(db.String(64), nullable=True)
    distributed_by = db.Column(db.String(120), nullable=True)  # Staff, Coordinator, or Trustee name
    
    created_at = db.Column(db.DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc))

    def __repr__(self):
        return f"<BeneficiaryAid #{self.id} for Beneficiary #{self.beneficiary_id} - {self.aid_type}>"
