from dataclasses import asdict, dataclass, field
from datetime import date, timedelta
import hashlib
import json
import time
from typing import Any
from django.core.cache import cache
from django.db.models import Q, QuerySet
from django.utils import timezone

from apps.accounts_rbac.constants import Permissions
from apps.accounts_rbac.models import CompanyMembership
from apps.accounts_rbac.policies import scope_queryset
from apps.localization.bs_calendar import ad_to_bs
from apps.reporting.models import CompanyLedgerWatermark, ReportExecutionRun, ReportRecentView
from apps.tenancy.models import FiscalYear


@dataclass
class ReportFilterContext:
    company_id: str
    fiscal_year_id: str = ""
    branch_id: str = ""
    department_id: str = ""
    project_id: str = ""
    site_id: str = ""
    cost_center_id: str = ""
    account_group_id: str = ""
    account_id: str = ""
    party_id: str = ""
    currency: str = "NPR"
    voucher_type: str = ""
    posted_status: str = "POSTED"  # POSTED | ALL | DRAFT | UNPOSTED | REVERSED
    compare_with: str = ""  # PREVIOUS_PERIOD | PREVIOUS_FY | BUDGET | ""
    date_preset: str = ""  # THIS_MONTH | PREV_MONTH | THIS_QUARTER | PREV_QUARTER | FY_CURRENT | FY_PREVIOUS | YTD | CUSTOM
    date_from: date | None = None
    date_to: date | None = None
    as_of_date: date | None = None
    date_display: str = "BOTH"  # AD | BS | BOTH
    include_zero: bool = False
    show_opening: bool = True
    show_narration: bool = True
    view_mode: str = "STANDARD"
    layout_mode: str = "MODERN_ENTERPRISE"
    group_by: str = ""
    sort_by: str = ""
    search: str = ""
    extra: dict = field(default_factory=dict)

    def to_fingerprint_dict(self) -> dict:
        d = asdict(self)
        for k in ("date_from", "date_to", "as_of_date"):
            if d.get(k):
                d[k] = d[k].isoformat()
        return d

    def fingerprint(self) -> str:
        raw = json.dumps(self.to_fingerprint_dict(), sort_keys=True, default=str)
        return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]


def _pdate(raw) -> date | None:
    if not raw:
        return None
    if isinstance(raw, date):
        return raw
    return date.fromisoformat(str(raw)[:10])


class ReportFilterEngine:
    """Normalizes common parameters, resolves AD/BS dates, enforces scope, and manages watermarked caches."""

    @staticmethod
    def resolve_dates(*, company, ctx: ReportFilterContext) -> ReportFilterContext:
        today = timezone.localdate()
        fy = None
        if ctx.fiscal_year_id:
            fy = FiscalYear.objects.filter(company=company, id=ctx.fiscal_year_id).first()
        if not fy:
            fy = FiscalYear.objects.filter(company=company, is_current=True).order_by("-start_date").first()

        preset = (ctx.date_preset or "").upper()
        if preset == "THIS_MONTH":
            ctx.date_from = today.replace(day=1)
            ctx.date_to = today
        elif preset == "PREV_MONTH":
            first = today.replace(day=1)
            last_prev = first - timedelta(days=1)
            ctx.date_from = last_prev.replace(day=1)
            ctx.date_to = last_prev
        elif preset == "THIS_QUARTER":
            q_month = ((today.month - 1) // 3) * 3 + 1
            ctx.date_from = date(today.year, q_month, 1)
            ctx.date_to = today
        elif preset == "PREV_QUARTER":
            q_month = ((today.month - 1) // 3) * 3 + 1
            curr_q_start = date(today.year, q_month, 1)
            prev_q_end = curr_q_start - timedelta(days=1)
            pq_month = ((prev_q_end.month - 1) // 3) * 3 + 1
            ctx.date_from = date(prev_q_end.year, pq_month, 1)
            ctx.date_to = prev_q_end
        elif preset == "FY_CURRENT" and fy:
            ctx.date_from = fy.start_date
            ctx.date_to = min(today, fy.end_date)
        elif preset == "FY_PREVIOUS":
            prev_fy = FiscalYear.objects.filter(company=company, end_date__lt=(fy.start_date if fy else today)).order_by("-end_date").first()
            if prev_fy:
                ctx.date_from = prev_fy.start_date
                ctx.date_to = prev_fy.end_date
        elif preset == "YTD":
            ctx.date_from = fy.start_date if fy else date(today.year, 1, 1)
            ctx.date_to = today

        if ctx.as_of_date and not ctx.date_to:
            ctx.date_to = ctx.as_of_date
        if not ctx.date_to:
            ctx.date_to = today
        if not ctx.as_of_date:
            ctx.as_of_date = ctx.date_to
        if not ctx.date_from and fy and fy.start_date <= ctx.date_to:
            ctx.date_from = fy.start_date
        if ctx.fiscal_year_id == "" and fy:
            ctx.fiscal_year_id = str(fy.id)
        return ctx

    @staticmethod
    def parse_request(*, company, params: dict) -> ReportFilterContext:
        ctx = ReportFilterContext(
            company_id=str(company.id),
            fiscal_year_id=str(params.get("fiscal_year") or params.get("fiscal_year_id") or ""),
            branch_id=str(params.get("branch") or params.get("branch_id") or ""),
            department_id=str(params.get("department") or params.get("department_id") or ""),
            project_id=str(params.get("project") or params.get("project_id") or ""),
            site_id=str(params.get("site") or params.get("site_id") or params.get("worksite") or ""),
            cost_center_id=str(params.get("cost_center") or params.get("cost_center_id") or ""),
            account_group_id=str(params.get("account_group") or params.get("ledger_group") or ""),
            account_id=str(params.get("account") or params.get("account_id") or ""),
            party_id=str(params.get("party") or params.get("party_id") or ""),
            currency=str(params.get("currency") or company.base_currency or "NPR").upper(),
            voucher_type=str(params.get("voucher_type") or ""),
            posted_status=str(params.get("posted_status") or "POSTED").upper(),
            compare_with=str(params.get("compare_with") or "").upper(),
            date_preset=str(params.get("date_preset") or ""),
            date_from=_pdate(params.get("date_from")),
            date_to=_pdate(params.get("date_to")),
            as_of_date=_pdate(params.get("as_of_date")),
            date_display=str(params.get("date_display") or "BOTH").upper(),
            include_zero=str(params.get("include_zero") or "false").lower() in ("1", "true", "yes"),
            show_opening=str(params.get("show_opening") or "true").lower() not in ("0", "false", "no"),
            show_narration=str(params.get("show_narration") or "true").lower() not in ("0", "false", "no"),
            view_mode=str(params.get("view_mode") or "STANDARD").upper(),
            layout_mode=str(params.get("layout_mode") or "MODERN_ENTERPRISE").upper(),
            group_by=str(params.get("group_by") or ""),
            sort_by=str(params.get("sort_by") or ""),
            search=str(params.get("search") or ""),
            extra={k: v for k, v in params.items() if k not in {
                "company", "fiscal_year", "fiscal_year_id", "branch", "branch_id", "department", "department_id",
                "project", "project_id", "site", "site_id", "worksite", "cost_center", "cost_center_id",
                "account_group", "ledger_group", "account", "account_id", "party", "party_id", "currency",
                "voucher_type", "posted_status", "compare_with", "date_preset", "date_from", "date_to",
                "as_of_date", "date_display", "include_zero", "show_opening", "show_narration", "view_mode",
                "layout_mode", "group_by", "sort_by", "search",
            }},
        )
        return ReportFilterEngine.resolve_dates(company=company, ctx=ctx)

    @staticmethod
    def scope_qs(qs: QuerySet, *, user, membership: CompanyMembership | None, project_field="project", site_field="site", branch_field="branch", is_project_model=False, is_site_model=False) -> QuerySet:
        if not membership or user.is_superuser:
            return qs
        perms = set(membership.effective_permissions())
        # Respect cross-project/cross-branch explicit permission overrides ONLY if data_scope permits or granted
        if membership.data_scope in (CompanyMembership.DataScope.BRANCH,) and Permissions.REPORT_CROSS_BRANCH in perms:
            pass
        elif membership.data_scope in (CompanyMembership.DataScope.PROJECT,) and Permissions.REPORT_CROSS_PROJECT in perms:
            pass
        else:
            qs = scope_queryset(
                qs,
                membership,
                user,
                project_field=project_field,
                site_field=site_field,
                branch_field=branch_field,
                is_project_model=is_project_model,
                is_site_model=is_site_model,
            )
        return qs

    @staticmethod
    def build_meta(*, company, ctx: ReportFilterContext, report_code: str, title: str, row_count: int = 0) -> dict:
        wm = CompanyLedgerWatermark.get_version(company.id)
        return {
            "report_code": report_code,
            "title": title,
            "company_id": str(company.id),
            "company_legal_name": company.name,
            "pan_vat_no": company.pan_vat_no,
            "address": getattr(company, "address", "") or "",
            "fiscal_year_id": ctx.fiscal_year_id,
            "currency": ctx.currency,
            "date_from": ctx.date_from.isoformat() if ctx.date_from else None,
            "date_to": ctx.date_to.isoformat() if ctx.date_to else None,
            "bs_date_from": ad_to_bs(ctx.date_from).isoformat() if ctx.date_from else None,
            "bs_date_to": ad_to_bs(ctx.date_to).isoformat() if ctx.date_to else None,
            "as_of_date": ctx.as_of_date.isoformat() if ctx.as_of_date else None,
            "generated_at": timezone.now().isoformat(),
            "ledger_watermark": wm,
            "filter_fingerprint": ctx.fingerprint(),
            "filters": ctx.to_fingerprint_dict(),
            "row_count": row_count,
        }

    @staticmethod
    def cached_execute(*, company, user, membership: CompanyMembership | None, report_code: str, title: str, ctx: ReportFilterContext, compute_fn, record_view: bool = True, output_format: str = "JSON") -> dict:
        t0 = time.monotonic()
        wm = CompanyLedgerWatermark.get_version(company.id)
        scope_key = f"{membership.data_scope if membership else 'SU'}:{','.join(str(x) for x in (membership.projects.values_list('id', flat=True) if membership else []))}"
        scope_hash = hashlib.md5(scope_key.encode()).hexdigest()[:10]
        cache_key = f"maya_rep:{company.id}:w{wm}:{report_code}:{scope_hash}:{ctx.fingerprint()}"

        result = cache.get(cache_key)
        if result is None:
            result = compute_fn()
            cache.set(cache_key, result, timeout=300)

        elapsed_ms = int((time.monotonic() - t0) * 1000)
        row_count = int(result.get("meta", {}).get("row_count") or len(result.get("rows") or []))

        if record_view and user and user.is_authenticated:
            ReportRecentView.objects.update_or_create(
                company=company,
                user=user,
                report_code=report_code,
                defaults={"report_title": title, "filters_json": ctx.to_fingerprint_dict()},
            )
            ReportExecutionRun.objects.create(
                company=company,
                fiscal_year_id=ctx.fiscal_year_id or None,
                report_code=report_code,
                report_title=title,
                filter_fingerprint=ctx.fingerprint(),
                filters_json=ctx.to_fingerprint_dict(),
                ledger_watermark=wm,
                output_format=output_format,
                row_count=row_count,
                generated_by=user,
                status="COMPLETED",
                duration_ms=elapsed_ms,
            )
        return result

