"""
Export Service for NGO Foundation Website.
Provides secure, permission-checked data extraction for Excel (.xlsx) and CSV formats.
Includes automatic defense against spreadsheet formula injection, strict exclusion of
sensitive identity and secret data, and audit logging for compliance.
Conforms to Section 13 (Reporting, Export, and Analytics) and Section 9.2 (Services Layer).
"""

import csv
from datetime import date, datetime, time, timezone
from io import BytesIO, StringIO
from openpyxl import Workbook
from flask import current_app, make_response
from sqlalchemy.exc import SQLAlchemyError

from app.extensions import db
from app.models.audit_log import AuditLog
from app.models.donation import Donation
from app.models.support_request import SupportRequest
from app.models.volunteer_application import VolunteerApplication


def sanitize_formula_injection(value):
    """
    Prevents CSV and Excel spreadsheet formula injection attacks (CSV injection / DDE).
    If a cell value starts with '=', '+', '-', '@', tab, or carriage return,
    it is prepended with a single quote (') so that spreadsheet programs treat it as plain text.

    Args:
        value (any): Raw cell value to inspect and sanitize.

    Returns:
        any: Sanitized cell value safe for CSV/Excel output.
    """
    if isinstance(value, str):
        stripped = value.lstrip(' \t\r\n')
        if stripped.startswith(('=', '+', '-', '@', '\t', '\r')):
            return "'" + value
    return value


def apply_date_range_filters(query, date_column, from_date_str=None, to_date_str=None):
    """
    Applies start and end date boundary filters to an active SQLAlchemy query.

    Args:
        query (Query): The SQLAlchemy query object.
        date_column (Column): The model DateTime column to filter on.
        from_date_str (str, optional): Start date string in 'YYYY-MM-DD' format.
        to_date_str (str, optional): End date string in 'YYYY-MM-DD' format.

    Returns:
        Query or None: Filtered SQLAlchemy query, or None if date string parsing fails.
    """
    try:
        if from_date_str:
            start_date = date.fromisoformat(from_date_str.strip())
            start_dt = datetime.combine(start_date, time.min)
            query = query.filter(date_column >= start_dt)
        if to_date_str:
            end_date = date.fromisoformat(to_date_str.strip())
            end_dt = datetime.combine(end_date, time.max)
            query = query.filter(date_column <= end_dt)
    except (ValueError, TypeError):
        return None
    return query


def generate_csv_response(filename, headers, rows, user_id, entity_name, safe_filter_metadata=""):
    """
    Constructs a streamed CSV HTTP response from provided rows, applying formula sanitization
    and recording an immutable audit log entry.

    Args:
        filename (str): Name of the download file (e.g., 'volunteer-report.csv').
        headers (list): List of column heading strings.
        rows (iterable): Iterable collection of row tuples or lists.
        user_id (int or str): Unique ID of the staff member generating the export.
        entity_name (str): The entity being exported (e.g., 'volunteer_applications').
        safe_filter_metadata (str): Sanitized description of applied filters (no PII).

    Returns:
        Response: Flask HTTP response with text/csv content type and attachment headers.
    """
    output = StringIO(newline='')
    writer = csv.writer(output)
    writer.writerow(headers)

    row_count = 0
    for row in rows:
        row_count += 1
        writer.writerow([sanitize_formula_injection(cell) for cell in row])

    # Record the export event in the AuditLog table for compliance tracking
    db.session.add(AuditLog(
        actor=str(user_id),
        action='export_csv',
        entity=entity_name,
        safe_metadata=f"{safe_filter_metadata}; row_count={row_count}",
    ))
    try:
        db.session.commit()
    except SQLAlchemyError:
        db.session.rollback()
        current_app.logger.exception("Failed to write audit log for CSV export.")

    response = make_response(output.getvalue())
    response.headers['Content-Type'] = 'text/csv; charset=utf-8'
    response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['Cache-Control'] = 'no-store'
    return response


def generate_xlsx_response(filename, headers, rows, user_id, entity_name, safe_filter_metadata=""):
    """
    Constructs an openpyxl Excel (.xlsx) workbook response with styling, auto-filter,
    column width adjustments, formula sanitization, and audit logging.

    Args:
        filename (str): Name of the download file (e.g., 'volunteers.xlsx').
        headers (list): List of column headers.
        rows (iterable): Iterable collection of data rows.
        user_id (int or str): Identity of the user requesting the export.
        entity_name (str): Name of exported entity for audit recording.
        safe_filter_metadata (str): Safe metadata describing filters applied.

    Returns:
        Response: Flask HTTP response containing binary workbook data.
    """
    wb = Workbook()
    ws = wb.active
    ws.title = "Export"
    ws.append(headers)

    row_count = 0
    for row in rows:
        row_count += 1
        ws.append([sanitize_formula_injection(cell) for cell in row])

    # Freeze header row and enable Excel table auto-filter
    ws.freeze_panes = 'A2'
    if ws.max_row > 1:
        ws.auto_filter.ref = ws.dimensions

    # Auto-adjust column widths based on content lengths
    for col in ws.columns:
        col_letter = col[0].column_letter
        max_length = max((len(str(cell.value or '')) for cell in col), default=0)
        ws.column_dimensions[col_letter].width = min(max(max_length + 2, 12), 40)

    stream = BytesIO()
    wb.save(stream)
    wb.close()
    stream.seek(0)

    # Record the export action in audit logs
    db.session.add(AuditLog(
        actor=str(user_id),
        action='export_xlsx',
        entity=entity_name,
        safe_metadata=f"{safe_filter_metadata}; row_count={row_count}",
    ))
    try:
        db.session.commit()
    except SQLAlchemyError:
        db.session.rollback()
        current_app.logger.exception("Failed to write audit log for XLSX export.")

    response = make_response(stream.getvalue())
    response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['Cache-Control'] = 'no-store'
    return response


def export_volunteer_records(user, file_format="xlsx", from_date=None, to_date=None, status_filter=None):
    """
    Generates a permission-checked export of volunteer applications for Admin or Verifier.
    Verifiers are restricted to their assigned applications only.

    Args:
        user (User): The requesting staff user instance.
        file_format (str): 'xlsx' or 'csv'.
        from_date (str, optional): Start date string.
        to_date (str, optional): End date string.
        status_filter (str, optional): Specific status to filter by.

    Returns:
        tuple or Response: Flask response object or (error_dict, status_code).
    """
    query = VolunteerApplication.query
    if user.role.role_name == 'Verifier':
        query = query.filter_by(assigned_to=user.id)

    query = apply_date_range_filters(query, VolunteerApplication.submitted_at, from_date, to_date)
    if query is None:
        return {'error': 'Dates must follow the YYYY-MM-DD standard format'}, 400

    if status_filter:
        query = query.filter_by(status=status_filter.strip())

    records = query.order_by(VolunteerApplication.submitted_at.desc()).limit(10000).all()
    headers = ['Reference Number', 'Applicant Name', 'State', 'District', 'Status', 'Submission Date']
    rows = [
        (
            rec.reference_id,
            rec.name,
            rec.state,
            rec.district,
            rec.status,
            rec.submitted_at.strftime('%Y-%m-%d %H:%M:%S UTC') if rec.submitted_at else ''
        )
        for rec in records
    ]

    safe_meta = f"from={from_date or ''}; to={to_date or ''}; status={status_filter or ''}"
    filename = f"volunteer-applications.{file_format}"
    if file_format == 'csv':
        return generate_csv_response(filename, headers, rows, user.id, 'volunteer_applications', safe_meta)
    return generate_xlsx_response(filename, headers, rows, user.id, 'volunteer_applications', safe_meta)


def export_support_records(user, file_format="xlsx", from_date=None, to_date=None, status_filter=None, category_filter=None):
    """
    Generates a permission-checked export of support requests for Admin or Verifier.

    Args:
        user (User): The requesting staff user.
        file_format (str): 'xlsx' or 'csv'.
        from_date (str, optional): Start date.
        to_date (str, optional): End date.
        status_filter (str, optional): Specific application status.
        category_filter (str, optional): Support category.

    Returns:
        tuple or Response: Flask response object or (error_dict, status_code).
    """
    query = SupportRequest.query
    if user.role.role_name == 'Verifier':
        query = query.filter_by(assigned_to=user.id)

    query = apply_date_range_filters(query, SupportRequest.submitted_at, from_date, to_date)
    if query is None:
        return {'error': 'Dates must follow the YYYY-MM-DD standard format'}, 400

    if status_filter:
        query = query.filter_by(status=status_filter.strip())
    if category_filter:
        query = query.filter_by(category=category_filter.strip())

    records = query.order_by(SupportRequest.submitted_at.desc()).limit(10000).all()
    headers = ['Reference Number', 'Category', 'Location', 'Status', 'Submission Date']
    rows = [
        (
            rec.reference_no,
            rec.category,
            rec.location,
            rec.status,
            rec.submitted_at.strftime('%Y-%m-%d %H:%M:%S UTC') if rec.submitted_at else ''
        )
        for rec in records
    ]

    safe_meta = f"from={from_date or ''}; to={to_date or ''}; status={status_filter or ''}"
    filename = f"support-requests.{file_format}"
    if file_format == 'csv':
        return generate_csv_response(filename, headers, rows, user.id, 'support_requests', safe_meta)
    return generate_xlsx_response(filename, headers, rows, user.id, 'support_requests', safe_meta)


def export_donation_records(user, file_format="xlsx", from_date=None, to_date=None, status_filter=None):
    """
    Generates an authorized finance export of donation records for Admin or Finance roles.

    Args:
        user (User): The requesting staff user.
        file_format (str): 'xlsx' or 'csv'.
        from_date (str, optional): Start date string.
        to_date (str, optional): End date string.
        status_filter (str, optional): Specific reconciliation status.

    Returns:
        tuple or Response: Flask response object or (error_dict, status_code).
    """
    query = Donation.query
    query = apply_date_range_filters(query, Donation.donated_at, from_date, to_date)
    if query is None:
        return {'error': 'Dates must follow the YYYY-MM-DD standard format'}, 400

    if status_filter:
        query = query.filter_by(status=status_filter.strip())

    records = query.order_by(Donation.donated_at.desc()).limit(10000).all()
    headers = [
        'Internal Reference', 'Provider Reference', 'Amount', 'Currency',
        'Payment Method', 'Reconciliation Status', 'Reconciled At', 'Donation Date'
    ]
    rows = [
        (
            rec.transaction_id,
            rec.provider_transaction_id or '',
            f"{rec.amount:.2f}",
            rec.currency,
            rec.payment_method,
            rec.status,
            rec.reconciled_at.strftime('%Y-%m-%d %H:%M:%S UTC') if rec.reconciled_at else '',
            rec.donated_at.strftime('%Y-%m-%d %H:%M:%S UTC') if rec.donated_at else ''
        )
        for rec in records
    ]

    safe_meta = f"from={from_date or ''}; to={to_date or ''}; status={status_filter or ''}"
    filename = f"donations.{file_format}"
    if file_format == 'csv':
        return generate_csv_response(filename, headers, rows, user.id, 'donations', safe_meta)
    return generate_xlsx_response(filename, headers, rows, user.id, 'donations', safe_meta)
