# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Nonprofit Compliance Calendar Skill

Track IRS filing deadlines, state requirements, and compliance checklists.

No API required — uses a curated local database of filing rules and deadlines.
"""

import logging
from datetime import date, timedelta

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Curated compliance data
# ---------------------------------------------------------------------------

# IRS federal deadlines (month, day, description, form, applies_to)
_IRS_DEADLINES = [
    (1, 15, "Q4 estimated tax payment due", "Form 990-ES", "501(c)(3)"),
    (1, 31, "W-2 and 1099 forms due to recipients", "W-2/1099", "all"),
    (2, 28, "1099 forms due to IRS (paper)", "1099", "all"),
    (3, 15, "Form 990-T due (tax-exempt orgs with UBTI, calendar year)", "990-T", "501(c)(3)"),
    (3, 31, "1099 forms due to IRS (electronic)", "1099", "all"),
    (4, 15, "Q1 estimated tax payment due", "Form 990-ES", "501(c)(3)"),
    (5, 15, "Form 990/990-EZ/990-N due (calendar year)", "990", "501(c)(3)"),
    (6, 15, "Q2 estimated tax payment due", "Form 990-ES", "501(c)(3)"),
    (7, 15, "Form 990-PF due (private foundations, calendar year)", "990-PF", "private_foundation"),
    (8, 15, "Form 990 extension deadline (6-month)", "990 ext", "501(c)(3)"),
    (9, 15, "Q3 estimated tax payment due", "Form 990-ES", "501(c)(3)"),
    (11, 15, "Form 990-PF extension deadline (4-month)", "990-PF ext", "private_foundation"),
    (12, 31, "Charitable contribution receipts for donors", "Receipts", "501(c)(3)"),
]

# State registration renewal info (state, description, typical_month, notes)
_STATE_REQUIREMENTS = [
    (
        "CA",
        "Attorney General annual registration (RRF-1/CT-2)",
        4,
        "Due 4 months 15 days after fiscal year end",
    ),
    ("NY", "Charities Bureau CHAR500 filing", 5, "Due 4 months 15 days after fiscal year end"),
    ("FL", "Annual report to Division of Consumer Services", 3, "Due by March 31"),
    ("TX", "Annual report to Secretary of State", 5, "Due by May 15"),
    ("IL", "Attorney General AG990-IL filing", 6, "Due 6 months after fiscal year end"),
    ("PA", "BCO-10 annual registration", 8, "Due by August 31"),
    ("OH", "Annual report to Attorney General", 5, "Due by May 15"),
    ("MA", "Form PC annual filing", 5, "Due 4 months 15 days after fiscal year end"),
    ("VA", "Annual registration with VDACS", 9, "Due September 1"),
    ("WA", "Annual renewal with Charities Program", 5, "Due by May 31"),
    ("NJ", "CRI-300R annual registration", 6, "Due 6 months after fiscal year end"),
    ("GA", "Annual registration renewal with Secretary of State", 4, "Due by April 1"),
    ("CO", "Annual report to Secretary of State", 0, "Periodic — check specific date"),
    ("MN", "Annual report and registration", 6, "Due 6 months after fiscal year end"),
    ("NC", "Solicitation license renewal", 0, "Varies — check with Secretary of State"),
]

# Compliance checklist items
_CHECKLIST = [
    ("board_meetings", "Hold required board meetings (minimum quarterly recommended)"),
    ("minutes", "Document meeting minutes and board resolutions"),
    ("conflict_of_interest", "Annual conflict of interest policy review and disclosure"),
    ("d_and_o_insurance", "Review and renew D&O insurance policy"),
    ("financial_audit", "Annual financial audit or review (if required by state/grants)"),
    ("form_990", "File IRS Form 990/990-EZ/990-N by deadline"),
    ("state_registration", "Renew state charitable solicitation registrations"),
    ("donor_receipts", "Issue annual donation receipts to donors"),
    ("budget_approval", "Board approval of annual budget"),
    ("policies_review", "Review governance policies (whistleblower, document retention)"),
    ("grant_reports", "Submit required grant progress/financial reports"),
    ("payroll_tax", "File quarterly payroll tax returns (941)"),
    ("worker_comp", "Review workers compensation coverage"),
    ("lobbying_limits", "Track lobbying expenditures against IRS limits"),
    ("unrelated_business", "Monitor unrelated business income (UBTI)"),
]


# ---------------------------------------------------------------------------
# Tool handlers
# ---------------------------------------------------------------------------


def filing_deadlines(data: dict) -> str:
    """List upcoming IRS filing deadlines."""
    months_ahead = min(int(data.get("months_ahead", 6)), 12)
    org_type = data.get("org_type", "501(c)(3)")

    today = date.today()
    cutoff = today + timedelta(days=months_ahead * 30)

    lines = [f"**Upcoming IRS Deadlines** (next {months_ahead} months):", ""]

    found = 0
    for month, day, desc, form, applies in _IRS_DEADLINES:
        deadline = date(today.year, month, day)
        if deadline < today:
            deadline = date(today.year + 1, month, day)

        if deadline <= cutoff and (applies == "all" or applies == org_type):
            days_until = (deadline - today).days
            urgency = "URGENT" if days_until <= 14 else ("Soon" if days_until <= 30 else "")
            tag = f" **[{urgency}]**" if urgency else ""

            lines.append(f"- **{deadline.strftime('%b %d')}** — {desc}{tag}")
            lines.append(f"  Form: {form} | In {days_until} days")
            lines.append("")
            found += 1

    if found == 0:
        return f"No upcoming IRS deadlines in the next {months_ahead} months."

    return "\n".join(lines)


def state_requirements(data: dict) -> str:
    """List state-specific nonprofit registration requirements."""
    state = data.get("state", "").upper().strip()

    if state:
        matches = [s for s in _STATE_REQUIREMENTS if s[0] == state]
        if not matches:
            return f"No specific requirements found for {state}. Check your Secretary of State website."

        lines = [f"**{state} Nonprofit Requirements:**", ""]
        for st, desc, month, notes in matches:
            month_name = date(2026, month, 1).strftime("%B") if month > 0 else "Varies"
            lines.append(f"- {desc}")
            lines.append(f"  Typical deadline: {month_name}")
            lines.append(f"  Note: {notes}")
            lines.append("")
        return "\n".join(lines)

    lines = [f"**State Registration Requirements** ({len(_STATE_REQUIREMENTS)} states):", ""]
    for st, desc, month, notes in _STATE_REQUIREMENTS:
        month_name = date(2026, month, 1).strftime("%B") if month > 0 else "Varies"
        lines.append(f"- **{st}**: {desc} ({month_name})")

    lines.append("")
    lines.append("Use `state_requirements` with a state code for details.")
    return "\n".join(lines)


def compliance_checklist(data: dict) -> str:
    """Get the nonprofit compliance checklist."""
    category = data.get("category", "").lower()

    lines = ["**Nonprofit Compliance Checklist:**", ""]

    for key, desc in _CHECKLIST:
        if category and category not in key and category not in desc.lower():
            continue
        lines.append(f"- [ ] **{key.replace('_', ' ').title()}**: {desc}")

    if len(lines) == 2:
        return f"No checklist items matching '{category}'."

    lines.append("")
    lines.append(f"Total items: {len(lines) - 3}")
    return "\n".join(lines)


# ---------------------------------------------------------------------------
# Tool definitions
# ---------------------------------------------------------------------------

TOOLS = [
    {
        "name": "filing_deadlines",
        "description": "List upcoming IRS filing deadlines for nonprofits with urgency tags.",
        "input_schema": {
            "type": "object",
            "properties": {
                "months_ahead": {
                    "type": "integer",
                    "description": "Months to look ahead (1-12, default 6)",
                    "default": 6,
                },
                "org_type": {
                    "type": "string",
                    "description": "Organization type: 501(c)(3), private_foundation, all",
                    "default": "501(c)(3)",
                },
            },
        },
        "handler": filing_deadlines,
        "category": "compliance",
    },
    {
        "name": "state_requirements",
        "description": "List state-specific nonprofit registration and filing requirements.",
        "input_schema": {
            "type": "object",
            "properties": {
                "state": {
                    "type": "string",
                    "description": "State code (e.g., CA, NY). Omit for all states.",
                },
            },
        },
        "handler": state_requirements,
        "category": "compliance",
    },
    {
        "name": "compliance_checklist",
        "description": "Get a nonprofit compliance checklist with governance and filing items.",
        "input_schema": {
            "type": "object",
            "properties": {
                "category": {
                    "type": "string",
                    "description": "Filter by category keyword (e.g., 'tax', 'board', 'grant')",
                },
            },
        },
        "handler": compliance_checklist,
        "category": "compliance",
    },
]
