"""Recurring documents: a template creates a customer invoice, vendor bill or journal entry on a schedule.

Dates step from the start date (15 Jan monthly -> 15 Feb -> 15 Mar), so they never drift; a start on a month end
stays on month ends (30 Sep -> 31 Oct -> 30 Nov). Running catches up: every
occurrence due up to the run date is created, each in its own savepoint, so one failure (a lock date, say) stops only
that template and leaves the others done.
"""
import calendar
from datetime import date, timedelta

from .db import q, x
from .i18n import get_lang, t
from .ledger import AccountingError, audit, check_lock, company, compute_invoice_line, create_move, now, \
    post_invoice

FREQUENCIES = [("weekly", "Weekly"), ("monthly", "Monthly"), ("quarterly", "Quarterly"), ("yearly", "Yearly")]
KINDS = {"out_invoice": "Customer Invoice", "in_invoice": "Vendor Bill", "entry": "Journal Entry"}
MONTHS_AR = ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"]


def add_months(d, n):
    y, m = divmod(d.month - 1 + n, 12)
    y, m = d.year + y, m + 1
    return date(y, m, min(d.day, calendar.monthrange(y, m)[1]))


def occurrence(rec, n):
    """Date of the n-th document (0 = the first)."""
    start, every = date.fromisoformat(rec["start_date"]), max(int(rec["every"] or 1), 1)
    if rec["frequency"] == "weekly":
        return start + timedelta(weeks=every * n)
    months = {"monthly": 1, "quarterly": 3, "yearly": 12}[rec["frequency"]]
    d = add_months(start, months * every * n)
    if start.day == calendar.monthrange(start.year, start.month)[1]:  # started on a month end: stay on month ends
        d = d.replace(day=calendar.monthrange(d.year, d.month)[1])
    return d


def finished(rec, n):
    """True when the n-th document is beyond the end date or the number of documents."""
    if rec["max_count"] and n >= rec["max_count"]:
        return True
    return bool(rec["end_date"]) and occurrence(rec, n).isoformat() > rec["end_date"]


def upcoming(rec, count=6):
    n, out = rec["done_count"], []
    while len(out) < count and not finished(rec, n):
        out.append(occurrence(rec, n).isoformat())
        n += 1
    return out


def refresh(rec_id):
    """Recompute the next date and whether the template is finished."""
    rec = q("SELECT * FROM recurring WHERE id = ?", (rec_id,), one=True)
    n = rec["done_count"]
    if finished(rec, n):
        x("UPDATE recurring SET next_date = NULL, state = 'done' WHERE id = ?", (rec_id,))
    else:
        state = "active" if rec["state"] == "done" else rec["state"]
        x("UPDATE recurring SET next_date = ?, state = ? WHERE id = ?", (occurrence(rec, n).isoformat(), state, rec_id))


def fill(text, d):
    """Placeholders in descriptions and references: {month} October 2026, {year} 2026, {period} 2026-10,
    {date} 2026-10-01."""
    if not text:
        return text
    month = (MONTHS_AR[d.month - 1] if get_lang() == "ar" else calendar.month_name[d.month]) + f" {d.year}"
    return (text.replace("{month}", month).replace("{year}", str(d.year))
            .replace("{period}", d.strftime("%Y-%m")).replace("{date}", d.isoformat()))


def _create_invoice(rec, lines, d, user_id):
    dec = q("SELECT c.decimals FROM branches b JOIN currencies c ON c.code = b.currency WHERE b.id = ?",
            (rec["branch_id"],), one=True)["decimals"]
    built = []
    for ln in lines:
        rate = q("SELECT rate FROM taxes WHERE id = ?", (ln["tax_id"],), one=True)["rate"] if ln["tax_id"] else 0
        sub, tax = compute_invoice_line(ln["quantity"], ln["price_unit"], rate, dec)
        built.append((ln, sub, tax))
    untaxed, tax = sum(b[1] for b in built), sum(b[2] for b in built)
    due = (d + timedelta(days=rec["due_days"] or 0)).isoformat()
    inv_id = x("INSERT INTO invoices (branch_id, journal_id, kind, partner_id, date, due_date, ref, notes, state, "
               "amount_untaxed, amount_tax, amount_total, created_by, created_at) VALUES (?,?,?,?,?,?,?,?,'draft',?,?,?,?,?)",
               (rec["branch_id"], rec["journal_id"], rec["kind"], rec["partner_id"], d.isoformat(), due,
                fill(rec["ref"], d), fill(rec["notes"], d), untaxed, tax, untaxed + tax, user_id, now()))
    for i, (ln, sub, tx) in enumerate(built):
        x("INSERT INTO invoice_lines (invoice_id, sequence, product_id, description, account_id, quantity, price_unit, "
          "tax_id, subtotal, tax_amount, cost_centre_id) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
          (inv_id, i, ln["product_id"], fill(ln["description"], d), ln["account_id"], ln["quantity"], ln["price_unit"],
           ln["tax_id"], sub, tx, ln["cost_centre_id"]))
    if rec["auto_post"]:
        post_invoice(inv_id, user_id)
    return "invoice", inv_id


def _create_entry(rec, lines, d, user_id):
    move_lines = [{"account_id": ln["account_id"], "partner_id": ln["partner_id"], "label": fill(ln["description"], d),
                   "debit": ln["debit"], "credit": ln["credit"], "cost_centre_id": ln["cost_centre_id"]} for ln in lines]
    mid = create_move(rec["branch_id"], rec["journal_id"], d.isoformat(), move_lines, user_id, ref=fill(rec["ref"], d),
                      narration=fill(rec["notes"], d), post=bool(rec["auto_post"]))
    return "move", mid


def _email_invoice(inv_id, user_id):
    """Email a posted customer invoice to the customer; problems are noted, never fatal."""
    from .mailer import configured, send
    from .money import fmt
    from .pdf import invoice_pdf
    from .i18n import nm
    inv = q("SELECT * FROM invoices WHERE id = ?", (inv_id,), one=True)
    partner = q("SELECT * FROM partners WHERE id = ?", (inv["partner_id"],), one=True)
    if not partner["email"]:
        return t("not emailed: the customer has no email address")
    if not configured():
        return t("not emailed: the outgoing mail server is not set up")
    branch = q("SELECT * FROM branches WHERE id = ?", (inv["branch_id"],), one=True)
    dec = q("SELECT decimals FROM currencies WHERE code = ?", (branch["currency"],), one=True)["decimals"]
    lines = q("SELECT il.*, pr.code AS pcode, tx.rate AS trate FROM invoice_lines il LEFT JOIN products pr "
              "ON pr.id = il.product_id LEFT JOIN taxes tx ON tx.id = il.tax_id WHERE il.invoice_id = ? "
              "ORDER BY il.sequence, il.id", (inv_id,))
    data = invoice_pdf(company(), inv, lines, branch, partner, dec, inv["amount_total"])
    co = nm(company())
    body = (f"{t('Dear')} {nm(partner)},\n\n{t('Please find attached')} {t('Customer Invoice').lower()} {inv['number']} "
            f"{t('dated')} {inv['date']} {t('for')} {branch['currency']} {fmt(inv['amount_total'], dec)}, "
            f"{t('due on')} {inv['due_date']}.\n\n{t('Kind regards')},\n{co}")
    try:
        send(partner["email"], f"{t('Customer Invoice')} {inv['number']} — {co}", body,
             [(f"{inv['number'].replace('/', '-')}.pdf", data, "application/pdf")], kind="invoice", model="invoice",
             record_id=inv_id, partner_id=partner["id"], user_id=user_id)
    except AccountingError as e:
        return f"{t('not emailed')}: {e}"
    return None


def run(up_to, branch_ids, user_id=None, rec_ids=None):
    """Create every document due up to a date. Returns [{rec, date, model, id, error, note}]."""
    sql = "SELECT * FROM recurring WHERE state = 'active' AND next_date IS NOT NULL AND next_date <= ?"
    args = [up_to]
    if branch_ids is not None:
        if not branch_ids:
            return []
        sql += f" AND branch_id IN ({','.join('?' * len(branch_ids))})"
        args += list(branch_ids)
    if rec_ids:
        sql += f" AND id IN ({','.join('?' * len(rec_ids))})"
        args += list(rec_ids)
    results = []
    for rec in q(sql + " ORDER BY next_date, id", args):
        lines = q("SELECT * FROM recurring_lines WHERE recurring_id = ? ORDER BY sequence, id", (rec["id"],))
        while True:
            rec = q("SELECT * FROM recurring WHERE id = ?", (rec["id"],), one=True)
            n = rec["done_count"]
            if finished(rec, n) or occurrence(rec, n).isoformat() > up_to:
                break
            d = occurrence(rec, n)
            x("SAVEPOINT recurring_doc")
            try:
                if not lines:
                    raise AccountingError(t("Add at least one line."))
                check_lock(d.isoformat())  # a draft in a locked period could never be posted
                model, rid = (_create_entry if rec["kind"] == "entry" else _create_invoice)(rec, lines, d, user_id)
                x("INSERT INTO recurring_runs (recurring_id, date, model, record_id, created_by, created_at) "
                  "VALUES (?,?,?,?,?,?)", (rec["id"], d.isoformat(), model, rid, user_id, now()))
                x("UPDATE recurring SET done_count = done_count + 1, last_error = NULL WHERE id = ?", (rec["id"],))
                refresh(rec["id"])
                x("RELEASE recurring_doc")
            except AccountingError as e:
                x("ROLLBACK TO recurring_doc")
                x("RELEASE recurring_doc")
                x("UPDATE recurring SET last_error = ? WHERE id = ?", (f"{d.isoformat()}: {e}", rec["id"]))
                results.append({"rec": rec, "date": d.isoformat(), "model": None, "id": None, "error": str(e)})
                break
            note = None
            if model == "invoice" and rec["auto_post"] and rec["auto_email"] and rec["kind"] == "out_invoice":
                note = _email_invoice(rid, user_id)
            audit(user_id, "recurring", model, rid, rec["name"])
            results.append({"rec": rec, "date": d.isoformat(), "model": model, "id": rid, "error": None, "note": note})
    return results


def due_count(up_to, branch_ids):
    if not branch_ids:
        return 0
    rows = q(f"SELECT * FROM recurring WHERE state = 'active' AND next_date IS NOT NULL AND next_date <= ? "
             f"AND branch_id IN ({','.join('?' * len(branch_ids))})", [up_to] + list(branch_ids))
    total = 0
    for rec in rows:
        n = rec["done_count"]
        while not finished(rec, n) and occurrence(rec, n).isoformat() <= up_to:
            total += 1
            n += 1
    return total


def amount(rec):
    """Total of one document made from the template (tax included for invoices)."""
    lines = q("SELECT l.*, tx.rate FROM recurring_lines l LEFT JOIN taxes tx ON tx.id = l.tax_id WHERE l.recurring_id = ?",
              (rec["id"],))
    if rec["kind"] == "entry":
        return sum(ln["debit"] for ln in lines)
    return sum(round(ln["quantity"] * ln["price_unit"] * (1 + (ln["rate"] or 0) / 100)) for ln in lines)
