from datetime import date, timedelta

from sqlalchemy.orm import Session

from app.repositories.policy_repository import PolicyRepository
from app.schemas.dashboard import CompanyPolicyCount, DashboardResponse, RecentPolicyItem


class DashboardService:
    def __init__(self, db: Session):
        self.db = db
        self.policies = PolicyRepository(db)

    def get_summary(self, agency_id: int) -> DashboardResponse:
        today = date.today()
        week_end = today + timedelta(days=6)
        next_week_start = today + timedelta(days=7)
        next_week_end = today + timedelta(days=13)
        month_end = today + timedelta(days=30)

        company_counts = []
        for company_id, company_name, count in self.policies.company_wise_counts(agency_id):
            if count:
                company_counts.append(CompanyPolicyCount(company_id=company_id, company_name=company_name, count=count))

        recent = []
        for policy in self.policies.recent_uploads(agency_id):
            recent.append(
                RecentPolicyItem(
                    id=policy.id,
                    policy_number=policy.policy_number,
                    customer_name=policy.customer.name if policy.customer else "",
                    policy_end_date=policy.policy_end_date.isoformat() if policy.policy_end_date else None,
                    status=policy.status.value,
                )
            )

        return DashboardResponse(
            total_active_policies=self.policies.count_active(agency_id),
            expiring_today=self.policies.count_expiring_between(agency_id, today, today),
            expiring_this_week=self.policies.count_expiring_between(agency_id, today, week_end),
            expiring_next_week=self.policies.count_expiring_between(agency_id, next_week_start, next_week_end),
            expiring_this_month=self.policies.count_expiring_between(agency_id, today, month_end),
            total_pending_payments=self.policies.sum_pending_payments(agency_id),
            policies_with_pending_payments=self.policies.count_pending_payment_policies(agency_id),
            company_wise_counts=company_counts,
            recently_uploaded=recent,
        )
