from odoo import models
from datetime import date

class ReportBusinessPerformance(models.AbstractModel):
    _name = 'report.sos_sales.report_business_performance'
    _description = 'Business Performance Report'

    def _get_financial_year(self):
        current_date = date.today()
        start_year = current_date.year if current_date.month >= 4 else current_date.year - 1
        end_year = start_year + 1
        return f"FY {start_year}-{end_year}"


    def _get_report_values(self, docids, data=None):
        sales_person_id = data.get('sales_person_id') if data else False
        financial_year = self._get_financial_year()

        domain = [('financial_year', '=', financial_year)]
        if sales_person_id:
            domain.append(('sales_person', '=', sales_person_id))

        records = self.env['sos_sales_achievement_report'].search(domain, order="sales_person ASC")

        months = [
            'april', 'may', 'june', 'july', 'august', 'september',
            'october', 'november', 'december',
            'january', 'february', 'march'
        ]
        month_names = {
            'april': 'Apr', 'may': 'May', 'june': 'Jun', 'july': 'Jul',
            'august': 'Aug', 'september': 'Sep', 'october': 'Oct',
            'november': 'Nov', 'december': 'Dec',
            'january': 'Jan', 'february': 'Feb', 'march': 'Mar'
        }

        current_month = date.today().month
        if current_month >= 4:
            ytd_months = months[:current_month - 4 + 1]
            current_month_key = months[current_month - 4]
        else:
            ytd_months = months[:current_month + 9 + 1]
            current_month_key = months[current_month + 9]

        records = list(records)

        summary = {
            'target': {m: 0.0 for m in months},
            'sales': {m: 0.0 for m in months},
            'billed': {m: 0.0 for m in months},
            'yet_to_billed': {m: 0.0 for m in months},
            'collected': {m: 0.0 for m in months},
            'ytd': {
                'target': 0.0,
                'sales': 0.0,
                'sales_percentage': 0.0,
                'yet_to_billed': 0.0,
                'billed': 0.0,
                'collected': 0.0,
            }
        }

        for doc in records:
            ytd_target = 0.0
            ytd_sales = 0.0
            ytd_yet_to_billed = 0.0
            ytd_billed = 0.0
            ytd_collected = 0.0

            for m in months:
                summary['target'][m] += round(getattr(doc, f'planned_target_{m}', 0.0), 2)
                summary['sales'][m] += round(getattr(doc, f'actual_target_{m}', 0.0), 2)
                summary['yet_to_billed'][m] += round(getattr(doc, f'yet_to_billed_target_{m}', 0.0), 2)
                summary['billed'][m] += round(getattr(doc, f'billed_target_{m}', 0.0), 2)
                summary['collected'][m] += round(getattr(doc, f'collected_target_{m}', 0.0), 2)

            for m in ytd_months:
                ytd_target += round(getattr(doc, f'planned_target_{m}', 0.0), 2)
                ytd_sales += round(getattr(doc, f'actual_target_{m}', 0.0), 2)
                ytd_billed += round(getattr(doc, f'billed_target_{m}', 0.0), 2)
                ytd_collected += round(getattr(doc, f'collected_target_{m}', 0.0), 2)

                summary['ytd']['target'] += round(getattr(doc, f'planned_target_{m}', 0.0), 2)
                summary['ytd']['sales'] += round(getattr(doc, f'actual_target_{m}', 0.0), 2)
                summary['ytd']['billed'] += round(getattr(doc, f'billed_target_{m}', 0.0), 2)
                summary['ytd']['collected'] += round(getattr(doc, f'collected_target_{m}', 0.0), 2)

            # Override YTD "yet_to_billed" with only current month value
            ytd_yet_to_billed = round(getattr(doc, f'yet_to_billed_target_{current_month_key}', 0.0), 2)
            summary['ytd']['yet_to_billed'] += ytd_yet_to_billed

            # Assign as formatted string with 2 decimal places
            doc.ytd_target = "%.2f" % ytd_target
            doc.ytd_sales = "%.2f" % ytd_sales
            doc.ytd_billed = "%.2f" % ytd_billed
            doc.ytd_yet_to_billed = "%.2f" % ytd_yet_to_billed
            doc.ytd_collected = "%.2f" % ytd_collected
            doc.ytd_sales_percentage = "%.2f" % (
                (ytd_sales / ytd_target) * 100 if ytd_target else 0.0
            )

        if summary['ytd']['target']:
            summary['ytd']['sales_percentage'] = "%.2f" % (
                (summary['ytd']['sales'] / summary['ytd']['target']) * 100
            )
        else:
            summary['ytd']['sales_percentage'] = "0.00"

        for key in ['target', 'sales', 'billed', 'collected']:
            summary['ytd'][key] = "%.2f" % summary['ytd'][key]
        summary['ytd']['yet_to_billed'] = "%.2f" % summary['ytd']['yet_to_billed']
        current_month_index = months.index(current_month_key) if current_month_key in months else 0
        return {
            'doc_ids': [rec.id for rec in records],
            'doc_model': 'sos_sales_achievement_report',
            'docs': records,
            'financial_year': financial_year,
            'enumerated_months': list(enumerate(months)),
            'months': months,
            'month_names': month_names,
            'summary': summary,
            'ytd_months': ytd_months,
            'current_month_index': int(current_month_index), 
            'is_filtered_by_sales_person': bool(sales_person_id)
        }

