"""Supplier onboarding and vendor portal accounts (licensed module "portal").

1. A supplier opens the public registration link and fills in the company, contact and bank details with its
   documents (CR, VAT certificate, bank letter...). Nothing is created in the books.
2. The registration goes through the approval workflow ("Supplier Registration" rules). Reviewers can ask for more
   information: the supplier gets a private link to correct the form and resubmit.
3. On approval the vendor is created (approved, with its documents and bank details) together with a portal user.
   The user gets an activation link (valid 72 hours, used once) to choose a password; passwords are never emailed.
Tokens are random and only their SHA-256 hash is stored.
"""
import hashlib
import os
import re
import secrets
import uuid
from datetime import datetime, timedelta

from flask import current_app, url_for

from .db import q, x
from .i18n import t
from .ledger import AccountingError, audit, company, now

DOC_TYPES = ["Commercial Registration", "VAT Certificate", "Bank Letter", "Chamber of Commerce", "GOSI Certificate",
             "Zakat Certificate", "Trade License", "ISO Certificate", "Company Profile", "Other"]
REQUIRED_DOCS = ["Commercial Registration", "VAT Certificate", "Bank Letter"]
ALLOWED_EXT = {".pdf", ".png", ".jpg", ".jpeg"}
MAX_FILE = 10 * 1024 * 1024
ACTIVATION_HOURS = 72
EDIT_DAYS = 14
MAX_PER_HOUR = 5          # registrations from one address
LOCK_AFTER = 5            # failed logins
LOCK_MINUTES = 15
FIELDS = ("company_en", "company_ar", "cr_no", "vat_no", "category", "contact_person", "email", "phone", "address",
          "city", "country", "website", "bank_name", "iban", "account_name", "swift", "currency", "notes")


def enabled():
    from . import has
    return has("portal")


def token_hash(token):
    return hashlib.sha256(token.encode()).hexdigest()


def new_token():
    tok = secrets.token_urlsafe(32)
    return tok, token_hash(tok)


def stamp(delta):
    return (datetime.now() + delta).isoformat(timespec="seconds")


def public_url(endpoint, **kw):
    """Absolute link for emails: the company's public address when set, else this server."""
    from flask import has_request_context, request
    if has_request_context():
        path = url_for(endpoint, **kw)
    else:
        with current_app.test_request_context():
            path = url_for(endpoint, **kw)
    base = (company()["public_url"] or "").rstrip("/")
    if not base and has_request_context():
        base = request.host_url.rstrip("/")
    return base + path


# ---------------------------------------------------------------- validation

EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$")


def iban_ok(iban):
    s = re.sub(r"\s+", "", iban or "").upper()
    if not re.fullmatch(r"[A-Z]{2}\d{2}[A-Z0-9]{10,30}", s):
        return False
    num = "".join(str(int(ch, 36)) for ch in s[4:] + s[:4])
    return int(num) % 97 == 1


def clean(form):
    v = {k: (form.get(k) or "").strip() or None for k in FIELDS}
    v["email"] = (v["email"] or "").lower() or None
    v["iban"] = re.sub(r"\s+", "", v["iban"] or "").upper() or None
    v["vat_no"] = re.sub(r"\s+", "", v["vat_no"] or "") or None
    v["cr_no"] = re.sub(r"\s+", "", v["cr_no"] or "") or None
    errors = []
    for k, label in (("company_en", "Company name (English)"), ("cr_no", "Commercial registration no."),
                     ("vat_no", "VAT registration no."), ("contact_person", "Contact person"), ("email", "Email"),
                     ("phone", "Phone"), ("bank_name", "Bank name"), ("iban", "IBAN"), ("account_name", "Account name")):
        if not v[k]:
            errors.append(f"{t(label)}: {t('is required')}")
    if v["email"] and not EMAIL.match(v["email"]):
        errors.append(t("Enter a valid email address."))
    if v["vat_no"] and not re.fullmatch(r"\d{15}", v["vat_no"]) and (v["country"] or "Saudi Arabia") in ("Saudi Arabia", "SA", "KSA"):
        errors.append(t("A Saudi VAT number has 15 digits."))
    if v["iban"] and not iban_ok(v["iban"]):
        errors.append(t("The IBAN is not valid."))
    if not form.get("declaration"):
        errors.append(t("Confirm that the information is correct."))
    if errors:
        raise AccountingError(" · ".join(errors))
    return v


def duplicates(reg):
    """Existing vendors or open registrations with the same VAT number, CR number or email."""
    out = []
    for col, label in (("vat_no", "VAT"), ("cr_no", "CR")):
        if reg.get(col):
            for p in q(f"SELECT id, name_en FROM partners WHERE {col} = ? AND is_vendor = 1", (reg[col],)):
                out.append({"kind": "vendor", "id": p["id"], "name": p["name_en"], "field": label})
    if reg.get("email"):
        for p in q("SELECT pu.partner_id AS id, pa.name_en FROM portal_users pu JOIN partners pa ON pa.id = pu.partner_id "
                   "WHERE pu.email = ?", (reg["email"],)):
            out.append({"kind": "vendor", "id": p["id"], "name": p["name_en"], "field": t("Email")})
    return out


# ---------------------------------------------------------------- files

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


def store_file(file):
    ext = os.path.splitext(file.filename or "")[1].lower()
    if ext not in ALLOWED_EXT:
        raise AccountingError(f"{t('Upload PDF, PNG or JPG files only.')} ({file.filename})")
    data = file.read()
    if len(data) > MAX_FILE:
        raise AccountingError(f"{t('The file is larger than')} 10 MB: {file.filename}")
    if not data:
        raise AccountingError(f"{t('The file is empty.')} ({file.filename})")
    if ext == ".pdf" and not data.startswith(b"%PDF"):
        raise AccountingError(f"{t('The file is not a valid PDF.')} ({file.filename})")
    stored = f"reg-{uuid.uuid4().hex}{ext}"
    with open(os.path.join(folder(), stored), "wb") as f:
        f.write(data)
    name = os.path.basename((file.filename or "").replace("\\", "/")).strip()[:150] or f"document{ext}"
    return stored, name


def add_docs(rid, docs):
    """docs: [(doc_type, number, expiry, FileStorage)]"""
    for doc_type, number, expiry, file in docs:
        stored, name = store_file(file)
        x("INSERT INTO vendor_registration_docs (registration_id, doc_type, number, expiry_date, filename, original_name, "
          "uploaded_at) VALUES (?,?,?,?,?,?,?)",
          (rid, doc_type if doc_type in DOC_TYPES else "Other", number, expiry or None, stored, name, now()))


def missing_docs(rid):
    have = {r[0] for r in q("SELECT doc_type FROM vendor_registration_docs WHERE registration_id = ?", (rid,))}
    return [d for d in REQUIRED_DOCS if d not in have]


# ---------------------------------------------------------------- registration

def too_many(ip):
    since = (datetime.now() - timedelta(hours=1)).isoformat(timespec="seconds")
    return q("SELECT COUNT(*) FROM vendor_registrations WHERE ip = ? AND created_at >= ?", (ip, since), one=True)[0] \
        >= MAX_PER_HOUR


def next_reg_number():
    year = datetime.now().year
    last = q("SELECT number FROM vendor_registrations WHERE number LIKE ? ORDER BY id DESC LIMIT 1", (f"REG/{year}/%",),
             one=True)
    n = int(last["number"].rsplit("/", 1)[1]) + 1 if last else 1
    return f"REG/{year}/{n:04d}"


def register(vals, docs, ip=None):
    """A new supplier registration from the public form. Returns its id."""
    if ip and too_many(ip):
        raise AccountingError(t("Too many registrations from this connection. Please try again later."))
    miss = [d for d in REQUIRED_DOCS if d not in {doc[0] for doc in docs}]
    if miss:
        raise AccountingError(f"{t('Attach these documents')}: " + ", ".join(t(m) for m in miss))
    dup = [d for d in duplicates(vals) if d["field"] in ("VAT", "CR")]
    if dup:
        raise AccountingError(t("A supplier with this VAT or CR number is already registered with us. "
                                "Please contact our procurement team."))
    if q("SELECT 1 FROM vendor_registrations WHERE state IN ('submitted', 'info_requested') AND (vat_no = ? OR cr_no = ?)",
         (vals["vat_no"], vals["cr_no"]), one=True):
        raise AccountingError(t("A registration with this VAT or CR number is already being reviewed."))
    cols = list(FIELDS) + ["number", "state", "declaration", "ip", "submitted_at", "created_at"]
    row = {**vals, "number": next_reg_number(), "state": "submitted", "declaration": 1, "ip": ip,
           "submitted_at": now(), "created_at": now()}
    rid = x(f"INSERT INTO vendor_registrations ({', '.join(cols)}) VALUES ({', '.join('?' * len(cols))})",
            [row[c] for c in cols])
    add_docs(rid, docs)
    _start_review(rid)
    _mail_applicant(rid, f"{t('Registration received')} {row['number']}",
                    f"{t('Thank you for registering as a supplier with')} {company()['name_en']}. "
                    f"{t('Your reference is')} {row['number']}. {t('We will email you when it has been reviewed.')}")
    audit(None, "register", "vendor_registration", rid, vals["company_en"])
    return rid


def _start_review(rid):
    from . import workflow
    reg = get(rid)
    workflow.submit("vendor_registration", rid, 0, f"{reg['number']} {reg['company_en']}", None)
    # without a matching rule the registration simply waits for an administrator or approver


def get(rid):
    return q("SELECT * FROM vendor_registrations WHERE id = ?", (rid,), one=True)


def by_edit_token(token):
    reg = q("SELECT * FROM vendor_registrations WHERE edit_token_hash = ?", (token_hash(token or ""),), one=True)
    if not reg or reg["state"] != "info_requested" or (reg["edit_token_expires"] or "") < now():
        return None
    return reg


def request_info(rid, message, user_id):
    """Ask the supplier to correct or complete the registration; returns the private link."""
    from . import workflow
    reg = get(rid)
    if reg["state"] != "submitted":
        raise AccountingError(t("This action is not allowed in the current state."))
    if not (message or "").strip():
        raise AccountingError(t("Write what the supplier should correct or add."))
    tok, h = new_token()
    x("UPDATE vendor_registrations SET state = 'info_requested', info_message = ?, edit_token_hash = ?, "
      "edit_token_expires = ? WHERE id = ?", (message.strip(), h, stamp(timedelta(days=EDIT_DAYS)), rid))
    workflow.cancel("vendor_registration", rid, user_id, t("More information requested"))
    link = public_url("supplier.register_edit", token=tok)
    _mail_applicant(rid, f"{t('More information needed')} — {reg['number']}",
                    f"{message.strip()}\n\n{t('Correct your registration here (the link works for 14 days)')}:\n{link}")
    audit(user_id, "request_info", "vendor_registration", rid)
    return link


def resubmit(token, vals, docs):
    reg = by_edit_token(token)
    if not reg:
        raise AccountingError(t("This link is no longer valid."))
    x(f"UPDATE vendor_registrations SET {', '.join(k + ' = ?' for k in FIELDS)}, state = 'submitted', "
      f"submitted_at = ?, edit_token_hash = NULL, edit_token_expires = NULL WHERE id = ?",
      [vals[k] for k in FIELDS] + [now(), reg["id"]])
    add_docs(reg["id"], docs)
    miss = missing_docs(reg["id"])
    if miss:
        raise AccountingError(f"{t('Attach these documents')}: " + ", ".join(t(m) for m in miss))
    _start_review(reg["id"])
    audit(None, "resubmit", "vendor_registration", reg["id"])
    return reg["id"]


def reject(rid, reason, user_id):
    from . import workflow
    reg = get(rid)
    if reg["state"] not in ("submitted", "info_requested"):
        raise AccountingError(t("This action is not allowed in the current state."))
    if not (reason or "").strip():
        raise AccountingError(t("Give the reason."))
    if q("SELECT 1 FROM approval_requests WHERE doc_type = 'vendor_registration' AND doc_id = ? AND state = 'pending'",
         (rid,), one=True):
        workflow.act_on_doc("vendor_registration", rid, user_id, "reject", reason)
        return
    _rejected(rid, user_id, reason)


def _rejected(rid, user_id, reason):
    reg = get(rid)
    x("UPDATE vendor_registrations SET state = 'rejected', reject_reason = ?, decided_by = ?, decided_at = ?, "
      "edit_token_hash = NULL WHERE id = ?", (reason, user_id, now(), rid))
    _mail_applicant(rid, f"{t('Supplier registration')} {reg['number']}",
                    f"{t('We are unable to approve your registration at this time.')}\n{reason or ''}")
    audit(user_id, "reject", "vendor_registration", rid, reason)


def approve(rid, user_id, override=False, reason=None):
    """Approve through the workflow; without an open approval request, an approver or administrator approves."""
    from . import workflow
    reg = get(rid)
    if reg["state"] != "submitted":
        raise AccountingError(t("This action is not allowed in the current state."))
    if q("SELECT 1 FROM approval_requests WHERE doc_type = 'vendor_registration' AND doc_id = ? AND state = 'pending'",
         (rid,), one=True):
        workflow.act_on_doc("vendor_registration", rid, user_id, "approve", reason, override)
        return get(rid)["partner_id"]
    return _approved(rid, user_id)


def _approved(rid, user_id):
    """Create the vendor with its documents and bank details, and its portal user with an activation link."""
    reg = get(rid)
    if reg["partner_id"]:
        return reg["partner_id"]
    terms = 30
    pid = x("INSERT INTO partners (name_en, name_ar, is_vendor, vat_no, cr_no, email, phone, address, website, "
            "vendor_status, vendor_category, payment_terms, contact_person, bank_name, iban, account_name, swift, "
            "currency, registration_id) VALUES (?,?,1,?,?,?,?,?,?,'approved',?,?,?,?,?,?,?,?,?)",
            (reg["company_en"], reg["company_ar"], reg["vat_no"], reg["cr_no"], reg["email"], reg["phone"],
             ", ".join(filter(None, [reg["address"], reg["city"], reg["country"]])) or None, reg["website"],
             reg["category"], terms, reg["contact_person"], reg["bank_name"], reg["iban"], reg["account_name"],
             reg["swift"], reg["currency"], rid))
    for d in q("SELECT * FROM vendor_registration_docs WHERE registration_id = ?", (rid,)):
        x("INSERT INTO vendor_documents (partner_id, doc_type, number, expiry_date, filename, original_name, uploaded_at) "
          "VALUES (?,?,?,?,?,?,?)", (pid, d["doc_type"], d["number"], d["expiry_date"], d["filename"], d["original_name"],
                                     d["uploaded_at"]))
    x("UPDATE vendor_registrations SET state = 'approved', partner_id = ?, decided_by = ?, decided_at = ? WHERE id = ?",
      (pid, user_id, now(), rid))
    link = invite_user(pid, reg["email"], reg["contact_person"], user_id, welcome=True)
    audit(user_id, "approve", "vendor_registration", rid, f"vendor {pid}")
    from flask import g, has_app_context
    if has_app_context():
        g.portal_link = link  # shown to the approver when email is not set up
    return pid


def _register_handlers():
    from . import workflow
    workflow.handler("vendor_registration", "approved")(_approved)
    workflow.handler("vendor_registration", "rejected")(_rejected)


_register_handlers()


def _mail_applicant(rid, subject, body):
    from . import mailer
    reg = get(rid)
    if not mailer.configured() or not reg["email"]:
        return False
    try:
        mailer.send(reg["email"], subject, body, kind="supplier", model="vendor_registration", record_id=rid)
        return True
    except AccountingError:
        return False


# ---------------------------------------------------------------- portal users

def invite_user(partner_id, email, name, user_id=None, welcome=False):
    """Create (or refresh) a portal user and email the activation link. Returns the link."""
    from . import mailer
    email = (email or "").strip().lower()
    if not EMAIL.match(email):
        raise AccountingError(t("Enter a valid email address."))
    tok, h = new_token()
    u = q("SELECT * FROM portal_users WHERE email = ?", (email,), one=True)
    if u and u["partner_id"] != partner_id:
        raise AccountingError(t("This email address already has a portal account for another vendor."))
    if u:
        x("UPDATE portal_users SET activation_hash = ?, activation_expires = ?, active = 1 WHERE id = ?",
          (h, stamp(timedelta(hours=ACTIVATION_HOURS)), u["id"]))
        uid = u["id"]
    else:
        uid = x("INSERT INTO portal_users (partner_id, email, full_name, activation_hash, activation_expires, created_by, "
                "created_at) VALUES (?,?,?,?,?,?,?)", (partner_id, email, name, h,
                                                       stamp(timedelta(hours=ACTIVATION_HOURS)), user_id, now()))
    link = public_url("supplier.activate", token=tok)
    p = q("SELECT name_en FROM partners WHERE id = ?", (partner_id,), one=True)
    if mailer.configured():
        body = (f"{t('Your supplier registration has been approved.')}\n\n" if welcome else "") + \
            f"{t('Activate your supplier portal account for')} {p['name_en']} {t('and choose your password')}:\n{link}\n\n" \
            f"{t('The link works once and expires in 72 hours. We never send passwords by email.')}"
        try:
            mailer.send(email, f"{company()['name_en']} — {t('Supplier portal account')}", body, kind="supplier",
                        partner_id=partner_id, user_id=user_id)
        except AccountingError:
            pass
    audit(user_id, "portal_invite", "vendor", partner_id, email)
    return link


def user_by_activation(token):
    u = q("SELECT * FROM portal_users WHERE activation_hash = ?", (token_hash(token or ""),), one=True)
    if not u or (u["activation_expires"] or "") < now() or not u["active"]:
        return None
    return u


def password_problem(pwd, confirm):
    if len(pwd or "") < 10:
        return t("Use at least 10 characters.")
    if not (re.search(r"[A-Za-z]", pwd) and re.search(r"\d", pwd)):
        return t("Use letters and numbers.")
    if pwd != confirm:
        return t("The two passwords are not the same.")
    return None


def activate(token, pwd, confirm):
    from werkzeug.security import generate_password_hash
    u = user_by_activation(token)
    if not u:
        raise AccountingError(t("This link is no longer valid. Ask us for a new one."))
    err = password_problem(pwd, confirm)
    if err:
        raise AccountingError(err)
    x("UPDATE portal_users SET password_hash = ?, activation_hash = NULL, activation_expires = NULL, activated_at = ?, "
      "failed_logins = 0, locked_until = NULL WHERE id = ?",
      (generate_password_hash(pwd, method="pbkdf2:sha256"), now(), u["id"]))
    return u["id"]


def login(email, pwd):
    """The portal user, or None. Five wrong passwords lock the account for 15 minutes."""
    from werkzeug.security import check_password_hash
    u = q("SELECT pu.*, p.vendor_status, p.active AS partner_active FROM portal_users pu JOIN partners p "
          "ON p.id = pu.partner_id WHERE pu.email = ?", ((email or "").strip().lower(),), one=True)
    if not u or not u["password_hash"] or not u["active"] or not u["partner_active"] or u["vendor_status"] == "blocked":
        return None
    if u["locked_until"] and u["locked_until"] > now():
        raise AccountingError(t("Too many attempts. Try again in a few minutes."))
    if not check_password_hash(u["password_hash"], pwd or ""):
        fails = u["failed_logins"] + 1
        x("UPDATE portal_users SET failed_logins = ?, locked_until = ? WHERE id = ?",
          (0 if fails >= LOCK_AFTER else fails, stamp(timedelta(minutes=LOCK_MINUTES)) if fails >= LOCK_AFTER else None,
           u["id"]))
        return None
    x("UPDATE portal_users SET failed_logins = 0, locked_until = NULL, last_login = ? WHERE id = ?", (now(), u["id"]))
    return u
