"""Supporting documents attached to invoices, payments, journal entries and other records.

Files live under instance/uploads/attachments/<year>/<month>/ with a random name; the table keeps the original
name. Only this module touches the files, so moving them to cloud storage later means changing save/path/remove.
"""
import os
import uuid
from datetime import datetime

from flask import current_app, url_for

from .db import q, x
from .i18n import t
from .ledger import AccountingError

MAX_SIZE = 15 * 1024 * 1024
ALLOWED = {".pdf", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".heic", ".doc", ".docx", ".xls", ".xlsx", ".csv", ".txt",
           ".eml", ".msg", ".zip"}
# shown in the browser; everything else downloads (never inline HTML/SVG, which could run scripts)
INLINE = {".pdf": "application/pdf", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
          ".webp": "image/webp", ".gif": "image/gif", ".txt": "text/plain"}

# model -> (table, view endpoint, view argument name)
RECORDS = {
    "invoice": ("invoices", "invoices.view", "inv_id"),
    "payment": ("payments", "payments.view", "pid"),
    "move": ("moves", "entries.view", "move_id"),
    "order": ("orders", "orders.view", "order_id"),
    "rfq": ("rfqs", "procurement.rfq_view", "rfq_id"),
    "picking": ("pickings", "inventory.picking", "picking_id"),
    "landed_cost": ("landed_costs", "inventory.landed_view", "lc_id"),
    "asset": ("assets", "assets.view", "asset_id"),
    "prepaid": ("prepaid_schedules", "prepaid.view", "sid"),
    "employee": ("employees", "hr.employee", "eid"),
    "petty_cash": ("petty_cash_vouchers", "pettycash.voucher", "vid"),
}


def root():
    path = os.path.join(os.path.dirname(current_app.config["DATABASE"]), "uploads", "attachments")
    os.makedirs(path, exist_ok=True)
    return path


def record(model, rid):
    """The record a file is attached to (raises KeyError for an unknown model)."""
    table = RECORDS[model][0]
    return q(f"SELECT * FROM {table} WHERE id = ?", (rid,), one=True)


def save(model, rid, file, user_id=None):
    ext = os.path.splitext(file.filename or "")[1].lower()
    if ext not in ALLOWED:
        raise AccountingError(f"{t('This file type is not allowed.')} ({file.filename})")
    file.stream.seek(0, os.SEEK_END)
    size = file.stream.tell()
    file.stream.seek(0)
    if size > MAX_SIZE:
        raise AccountingError(f"{t('The file is larger than')} {MAX_SIZE // (1024 * 1024)} MB: {file.filename}")
    if size == 0:
        raise AccountingError(f"{t('The file is empty.')} ({file.filename})")
    sub = datetime.now().strftime("%Y/%m")
    os.makedirs(os.path.join(root(), sub), exist_ok=True)
    stored = f"{sub}/{uuid.uuid4().hex}{ext}"
    file.save(os.path.join(root(), stored))
    name = os.path.basename((file.filename or "").replace("\\", "/")).strip() or f"document{ext}"
    return x("INSERT INTO attachments (model, record_id, filename, stored, content_type, size, uploaded_by, uploaded_at) "
             "VALUES (?,?,?,?,?,?,?,?)", (model, rid, name[:200], stored, INLINE.get(ext, "application/octet-stream"),
                                          size, user_id, datetime.now().isoformat(timespec="seconds")))


def path(att):
    full = os.path.realpath(os.path.join(root(), att["stored"]))
    if not full.startswith(os.path.realpath(root()) + os.sep):
        raise FileNotFoundError(att["stored"])
    return full


def remove(att):
    x("DELETE FROM attachments WHERE id = ?", (att["id"],))
    try:
        os.remove(path(att))
    except OSError:
        pass


def remove_all(model, rid):
    """When a draft document is deleted."""
    for att in q("SELECT * FROM attachments WHERE model = ? AND record_id = ?", (model, rid)):
        remove(att)


def listing(model, rid):
    """Files on a record; a journal entry also shows those of the document that created it."""
    rows = [dict(r, source=None) for r in q(
        "SELECT a.*, u.username FROM attachments a LEFT JOIN users u ON u.id = a.uploaded_by "
        "WHERE a.model = ? AND a.record_id = ? ORDER BY a.id", (model, rid))]
    if model == "move":
        for src, table, label in (("invoice", "invoices", "number"), ("payment", "payments", "name"),
                                  ("picking", "pickings", "number"), ("landed_cost", "landed_costs", "number")):
            _, endpoint, arg = RECORDS[src]
            for doc in q(f"SELECT id, {label} AS label FROM {table} WHERE move_id = ?", (rid,)):
                link = (doc["label"] or "", url_for(endpoint, **{arg: doc["id"]}))
                rows += [dict(r, source=link) for r in q(
                    "SELECT a.*, u.username FROM attachments a LEFT JOIN users u ON u.id = a.uploaded_by "
                    "WHERE a.model = ? AND a.record_id = ? ORDER BY a.id", (src, doc["id"]))]
    return rows


def counts(model, ids):
    """{record id: number of files} for list pages."""
    ids = list(ids)
    if not ids:
        return {}
    return {r[0]: r[1] for r in q(f"SELECT record_id, COUNT(*) FROM attachments WHERE model = ? AND record_id IN "
                                  f"({','.join('?' * len(ids))}) GROUP BY record_id", [model] + ids)}
