import logging
import uuid6
from flask import current_app
from app.extensions import db
from app.modules.erp.models import Project, Invoice
from app.core.models import ContactMeta
from app.core.models import Status
from app.core.services.notification import NotificationService
from datetime import date, timedelta, datetime
from dateutil.relativedelta import relativedelta

logger = logging.getLogger(__name__)

def run_pending_schedules():
    """
    Checks for pending recurring tasks (invoices)
    and executes them. This function is idempotent.

    Returns:
        dict: A summary of jobs run.
    """
    logger.info("Running pending schedules (Lazy Evaluation)...")

    jobs_processed = 0

    # 1. Recurring Invoices Logic
    # Find projects that are recurring and due for invoicing
    today = date.today()
    recurring_projects = Project.query_active().filter(
        Project.project_type == 'recurring',
        Project.next_invoice_date <= today,
        Project.status.has(Status.system_tag == 'PROCESS') # Only active projects
    ).with_for_update(skip_locked=True).all()

    # Get Draft status for new invoices
    draft_status = Status.query.filter_by(module='erp', slug='inv_draft').first()
    if not draft_status:
        # Fallback
        draft_status = Status.query.filter_by(module='erp', system_tag='NEW').first()

    for project in recurring_projects:
        # Create Invoice
        new_invoice = Invoice(
            number=f"INV-{uuid6.uuid7().hex[:8].upper()}", # Placeholder number logic
            project_id=project.id,
            contact_id=project.contact_id,
            status_id=draft_status.id,
            issue_date=today,
            due_date=today + timedelta(days=14), # Default net 14
            amount=project.recurring_amount,
            notes=f"Recurring invoice for cycle {project.next_invoice_date.strftime('%Y-%m')}"
        )
        db.session.add(new_invoice)

        # Update Next Invoice Date
        if project.billing_cycle == 'monthly':
            project.next_invoice_date = project.next_invoice_date + relativedelta(months=1)
        elif project.billing_cycle == 'yearly':
            project.next_invoice_date = project.next_invoice_date + relativedelta(years=1)
        else:
            # Default fallback (monthly)
            project.next_invoice_date = project.next_invoice_date + relativedelta(months=1)

        jobs_processed += 1
        logger.info(f"Generated recurring invoice for Project {project.title}")

    if jobs_processed > 0:
        db.session.commit()

    # 2. Check Expiry Dates (Contact Meta)
    # Check for metadata of type 'date' that matches today (or approaching)
    # Simplified logic: exact match today for demo
    expiries = ContactMeta.query.filter_by(type='date').filter(ContactMeta.value == today.strftime('%Y-%m-%d')).all()

    for meta in expiries:
        # Notify who? Ideally Account Manager.
        # Fallback to Admin or System Notification log
        # For this prototype, we'll log it. In real app, check Contact owner.
        logger.info(f"Expiry Alert: {meta.key} for Contact ID {meta.contact_id} expires today.")
        # If we had owner: NotificationService.send(owner_id, ...)

    return {"status": "success", "jobs_processed": jobs_processed}
