from datetime import datetime, timedelta
from decimal import Decimal, InvalidOperation
import os
import secrets
import hashlib

from flask import abort, current_app, flash, redirect, render_template, request, session, url_for
from flask_login import current_user, login_required
from sqlalchemy import and_, func, or_
from werkzeug.security import generate_password_hash
from werkzeug.utils import secure_filename

from app import db
from app.audit import log_audit
from app.mail_utils import send_email
from app.models import (
    Currency,
    CountryMaster,
    LanguageMaster,
    LanguagePairMaster,
    Industry,
    LeadService,
    ServiceCategory,
    ServiceSubCategory,
    VendorBillingProfile,
    VendorEmailOTP,
    VendorPrivacyEvent,
    VendorMaster,
    VendorOnboardingProfile,
    VendorOnboardingDomain,
    VendorNDADocument,
    VendorNDASignature,
    VendorServiceCapability,
    VendorServiceRate,
    VendorRateNegotiationEvent,
    VendorServiceRequest,
    VendorServiceTest,
    VendorServiceWorkSample,
    VendorStatusHistory,
)
from app.utils import require_perm
from . import vendor_admin_bp, vendor_finance_bp, vendor_portal_bp
from .onboarding_ai import generate_test, score_test
from .routes import VENDOR_SESSION_KEY, get_current_vendor, vendor_login_required

OTP_HOURS = 24
ONBOARDING_GRACE_DAYS = 45
PRIVACY_NOTICE_VERSION = "2026-09-03"
ALLOWED_DOC_EXTENSIONS = {".pdf", ".jpg", ".jpeg", ".png", ".doc", ".docx"}
ALLOWED_SAMPLE_EXTENSIONS = ALLOWED_DOC_EXTENSIONS | {".txt", ".rtf", ".xlsx", ".xls", ".pptx", ".ppt", ".zip"}
STATUS_OPTIONS = ("ACTIVE", "INACTIVE", "ON_HOLD", "BLOCKED", "BLACKLISTED")
UNITS = ("Per Word", "Per Hour", "Per Page", "Per Minute", "Flat Rate")


def _now():
    return datetime.utcnow()


def _has_perm(code):
    return bool(current_user.is_authenticated and current_user.has_perm(code))


def _safe_decimal(value):
    try:
        return Decimal(str(value or "0"))
    except (InvalidOperation, ValueError, TypeError):
        return Decimal("0")


def _new_trans_id():
    prefix = "WEB-{}-".format(_now().strftime("%Y%m%d"))
    for _ in range(20):
        value = prefix + str(secrets.randbelow(9000) + 1000)
        if not VendorMaster.query.filter_by(external_translator_id=value).first():
            return value
    return prefix + secrets.token_hex(4).upper()


def _save_onboarding_file(file_obj, vendor_id, label):
    if not file_obj or not file_obj.filename:
        return None
    filename = secure_filename(file_obj.filename)
    ext = os.path.splitext(filename)[1].lower()
    if ext not in ALLOWED_DOC_EXTENSIONS:
        raise ValueError("Only PDF, image, DOC and DOCX files are allowed for verification documents.")
    root = os.path.join(current_app.root_path, "static", "uploads", "vendor_onboarding", str(vendor_id))
    os.makedirs(root, exist_ok=True)
    stored = "{}_{}_{}{}".format(label, _now().strftime("%Y%m%d%H%M%S"), secrets.token_hex(4), ext)
    file_obj.save(os.path.join(root, stored))
    return "uploads/vendor_onboarding/{}/{}".format(vendor_id, stored)




def _save_work_sample(file_obj, vendor_id, capability_id):
    if not file_obj or not file_obj.filename:
        return None
    original = secure_filename(file_obj.filename)
    ext = os.path.splitext(original)[1].lower()
    if ext not in ALLOWED_SAMPLE_EXTENSIONS:
        raise ValueError("Unsupported work sample type. Upload PDF, Office, image, text or ZIP files.")
    root = os.path.join(current_app.root_path, "static", "uploads", "vendor_onboarding", str(vendor_id), "work_samples")
    os.makedirs(root, exist_ok=True)
    stored = "service_{}_{}_{}{}".format(capability_id, _now().strftime("%Y%m%d%H%M%S"), secrets.token_hex(4), ext)
    file_obj.save(os.path.join(root, stored))
    return original, "uploads/vendor_onboarding/{}/work_samples/{}".format(vendor_id, stored)


def _file_sha256(path):
    digest = hashlib.sha256()
    with open(path, "rb") as handle:
        while True:
            chunk = handle.read(1024 * 1024)
            if not chunk:
                break
            digest.update(chunk)
    return digest.hexdigest()


def _current_nda(now=None):
    return VendorNDADocument.current(now or _now())


def _current_nda_signature(vendor, nda=None, now=None):
    nda = nda or _current_nda(now)
    if not nda:
        return None
    now = now or _now()
    return VendorNDASignature.query.filter_by(vendor_id=vendor.id, nda_document_id=nda.id).filter(VendorNDASignature.expires_at >= now).first()


def _active_countries():
    return CountryMaster.query.filter_by(is_active=True).order_by(CountryMaster.sort_order.asc(), CountryMaster.name.asc()).all()


def _active_currencies():
    return Currency.query.filter_by(is_active=True).order_by(Currency.sort_order.asc(), Currency.code.asc()).all()


def _sync_approved_onboarding_to_billing(vendor, profile):
    """Copy administrator-approved onboarding payment data into billing profile."""
    billing = vendor.billing_profile
    if not billing:
        billing = VendorBillingProfile(vendor_id=vendor.id)
        db.session.add(billing)
        db.session.flush()
    billing.beneficiary_name = profile.account_holder_name or vendor.name
    billing.billing_address = profile.address
    billing.bank_name = profile.bank_name
    billing.bank_account_number = profile.bank_account_number
    billing.ifsc_code = (profile.ifsc_code or '').upper() or None
    billing.swift_code = (profile.swift_code or '').upper() or None
    billing.iban = (profile.iban or '').upper() or None
    billing.paypal_id = profile.paypal_id
    billing.profile_confirmed_at = _now()
    billing.updated_at = _now()
    return billing

def _profile(vendor, create=True):
    profile = vendor.onboarding_profile
    if not profile and create:
        profile = VendorOnboardingProfile(vendor_id=vendor.id)
        db.session.add(profile)
        db.session.flush()
    return profile


def _latest_otp(vendor):
    return VendorEmailOTP.query.filter_by(vendor_id=vendor.id).order_by(VendorEmailOTP.id.desc()).first()


def _send_otp(vendor):
    otp_value = "{:06d}".format(secrets.randbelow(1000000))
    now = _now()
    otp = VendorEmailOTP(
        vendor_id=vendor.id,
        email=vendor.email,
        otp_hash=generate_password_hash(otp_value, method="pbkdf2:sha256"),
        otp_display=otp_value,
        expires_at=now + timedelta(hours=OTP_HOURS),
        email_status="PENDING",
    )
    db.session.add(otp)
    db.session.commit()

    subject = "Crystal Nexus Vendor Portal - Email verification OTP"
    body = (
        "Hello {},\n\nYour Crystal Nexus Vendor Portal verification OTP is {}.\n"
        "This OTP is valid for 24 hours.\n\nIf you did not request this registration, please ignore this email."
    ).format(vendor.name or "Vendor", otp_value)
    ok, error, mail_log_id = send_email(
        subject,
        [vendor.email],
        body,
        module="Vendor Onboarding",
        event="OTP",
        related_entity_type="VendorMaster",
        related_entity_id=vendor.id,
    )
    otp.email_status = "SENT" if ok else "FAILED"
    otp.email_error = error
    otp.mail_log_id = mail_log_id
    db.session.commit()
    return otp, ok, error


def _capability_ready(capability):
    if capability.status != "APPROVED":
        return False
    if capability.final_level not in (1, 2, 3, 4, 5):
        return False
    return True


def _recalculate_onboarding(vendor):
    profile = _profile(vendor, create=False)
    approved_capability = VendorServiceCapability.query.filter_by(vendor_id=vendor.id, status="APPROVED").first()
    current_nda = _current_nda()
    nda_ok = (current_nda is None) or bool(_current_nda_signature(vendor, current_nda))
    if profile and profile.verification_status == "APPROVED" and approved_capability and nda_ok:
        vendor.onboarding_status = "COMPLETED"
        if not vendor.onboarding_completed_at:
            vendor.onboarding_completed_at = _now()
    elif profile and profile.submitted_at:
        vendor.onboarding_status = "IN_PROGRESS"
        if vendor.onboarding_completed_at and not nda_ok:
            vendor.onboarding_completed_at = None
    db.session.flush()


def _ensure_existing_vendor_deadline(vendor):
    if (vendor.registration_source or "PMS").upper() != "WEBSITE" and not vendor.onboarding_due_at:
        vendor.onboarding_due_at = _now() + timedelta(days=ONBOARDING_GRACE_DAYS)
    if vendor.onboarding_status == "NOT_STARTED":
        vendor.onboarding_started_at = vendor.onboarding_started_at or _now()
        vendor.onboarding_status = "IN_PROGRESS"


@vendor_portal_bp.route("/signup", methods=["GET", "POST"])
def signup():
    if get_current_vendor():
        return redirect(url_for("vendor_portal.onboarding"))
    if request.method == "POST":
        name = (request.form.get("name") or "").strip()
        email = (request.form.get("email") or "").strip().lower()
        phone = (request.form.get("phone") or "").strip()
        password = request.form.get("password") or ""
        confirm = request.form.get("confirm_password") or ""
        privacy_ack = request.form.get("privacy_ack") == "1"
        if not privacy_ack:
            flash("Please review and acknowledge the Privacy Notice before creating your account.", "danger")
        elif not name or not email or "@" not in email:
            flash("Enter your name and a valid email address.", "danger")
        elif len(password) < 8:
            flash("Password must be at least 8 characters.", "danger")
        elif password != confirm:
            flash("Password confirmation does not match.", "danger")
        else:
            existing = VendorMaster.query.filter(func.lower(VendorMaster.email) == email).first()
            if existing:
                flash("This email is already registered. Please sign in to continue onboarding.", "warning")
                return redirect(url_for("vendor_portal.login"))
            vendor = VendorMaster(
                external_translator_id=_new_trans_id(),
                name=name,
                email=email,
                phone=phone or None,
                is_active=True,
                portal_active=True,
                portal_must_change_password=False,
                registration_source="WEBSITE",
                translator_status="ACTIVE",
                onboarding_status="IN_PROGRESS",
                onboarding_started_at=_now(),
                portal_created_at=_now(),
            )
            vendor.set_portal_password(password, must_change=False)
            db.session.add(vendor)
            db.session.flush()
            db.session.add(VendorOnboardingProfile(vendor_id=vendor.id, primary_phone=phone or None))
            db.session.add(VendorPrivacyEvent(
                vendor_id=vendor.id,
                event_type="NOTICE_ACKNOWLEDGED",
                policy_version=PRIVACY_NOTICE_VERSION,
            ))
            db.session.commit()
            otp, ok, error = _send_otp(vendor)
            session["vendor_signup_vendor_id"] = vendor.id
            flash("Verification OTP sent to your email." if ok else "Registration created, but the OTP email could not be sent. Please contact the Vendor Coordinator for the OTP.", "success" if ok else "warning")
            return redirect(url_for("vendor_portal.verify_signup_otp"))
    return render_template("vendor_portal/signup.html")


@vendor_portal_bp.route("/signup/verify", methods=["GET", "POST"])
def verify_signup_otp():
    vendor_id = session.get("vendor_signup_vendor_id")
    vendor = VendorMaster.query.get(vendor_id) if vendor_id else None
    if not vendor:
        flash("Registration session expired. Please sign in or register again.", "warning")
        return redirect(url_for("vendor_portal.signup"))
    otp = _latest_otp(vendor)
    if request.method == "POST":
        value = (request.form.get("otp") or "").strip()
        if not otp or not otp.is_valid(value):
            flash("Invalid or expired OTP.", "danger")
        else:
            otp.verified_at = _now()
            vendor.email_verified_at = _now()
            vendor.portal_active = True
            db.session.commit()
            session[VENDOR_SESSION_KEY] = vendor.id
            session.pop("vendor_signup_vendor_id", None)
            flash("Email verified successfully. Complete your onboarding profile and save as often as needed.", "success")
            return redirect(url_for("vendor_portal.onboarding"))
    return render_template("vendor_portal/verify_otp.html", vendor=vendor, otp=otp)


@vendor_portal_bp.route("/signup/resend-otp", methods=["POST"])
def resend_signup_otp():
    vendor_id = session.get("vendor_signup_vendor_id")
    vendor = VendorMaster.query.get(vendor_id) if vendor_id else None
    if not vendor:
        abort(404)
    _send_otp(vendor)
    flash("A new 24-hour OTP has been generated.", "success")
    return redirect(url_for("vendor_portal.verify_signup_otp"))


@vendor_portal_bp.route("/onboarding", methods=["GET", "POST"])
@vendor_login_required
def onboarding():
    vendor = get_current_vendor()
    _ensure_existing_vendor_deadline(vendor)
    profile = _profile(vendor)
    if request.method == "POST":
        if vendor.onboarding_completed_at or (vendor.onboarding_status or "").upper() == "COMPLETED":
            flash("Completed onboarding is read-only. Use My Profile to request changes or add another service.", "info")
            return redirect(url_for("vendor_portal.onboarding"))
        action = request.form.get("action") or "save"
        vendor.name = (request.form.get("name") or vendor.name or "").strip()
        vendor.phone = (request.form.get("primary_phone") or vendor.phone or "").strip() or None
        profile.primary_phone = (request.form.get("primary_phone") or "").strip() or None
        profile.secondary_phone = (request.form.get("secondary_phone") or "").strip() or None

        dob_raw = (request.form.get("date_of_birth") or "").strip()
        try:
            profile.date_of_birth = datetime.strptime(dob_raw, "%Y-%m-%d").date() if dob_raw else None
        except ValueError:
            flash("Enter a valid Date of Birth.", "danger")
            return redirect(url_for("vendor_portal.onboarding"))
        if profile.date_of_birth and profile.date_of_birth > _now().date():
            flash("Date of Birth cannot be in the future.", "danger")
            return redirect(url_for("vendor_portal.onboarding"))

        gender = (request.form.get("gender") or "").strip()
        allowed_genders = {"Male", "Female", "Non-binary", "Prefer not to say", "Other"}
        profile.gender = gender if gender in allowed_genders else None

        exp_raw = (request.form.get("years_of_experience") or "").strip()
        try:
            experience = Decimal(exp_raw) if exp_raw else None
        except (InvalidOperation, ValueError, TypeError):
            experience = None
        if exp_raw and (experience is None or experience < 0):
            flash("Years of experience must be a valid non-negative number.", "danger")
            return redirect(url_for("vendor_portal.onboarding"))
        profile.years_of_experience = experience

        native_language_value = (request.form.get("native_language") or "").strip()
        native_language_other = (request.form.get("native_language_other") or "").strip()
        if native_language_value == "OTHER":
            if not native_language_other:
                flash("Please specify the native language when Others is selected.", "danger")
                return redirect(url_for("vendor_portal.onboarding"))
            profile.native_language_id = None
            profile.native_language_other = native_language_other
        else:
            try:
                native_language_id = int(native_language_value) if native_language_value else None
            except (TypeError, ValueError):
                native_language_id = None
            native_language = LanguageMaster.query.filter_by(id=native_language_id, is_active=True).first() if native_language_id else None
            profile.native_language_id = native_language.id if native_language else None
            profile.native_language_other = None

        voice_modulation = (request.form.get("voice_modulation_type") or "").strip()
        allowed_voice_modulation = {"Not Applicable", "Neutral / Standard", "Corporate / Narration", "Commercial / Promotional", "E-learning", "Dubbing / Lip-sync", "Character / Animation", "Audiobook / Storytelling", "IVR / Telephony", "Other"}
        profile.voice_modulation_type = voice_modulation if voice_modulation in allowed_voice_modulation else None

        selected_domain_ids = []
        for raw_domain_id in request.form.getlist("domain_ids"):
            try:
                selected_domain_ids.append(int(raw_domain_id))
            except (TypeError, ValueError):
                pass
        selected_domain_ids = sorted(set(selected_domain_ids))
        valid_industries = Industry.query.filter(Industry.is_active.is_(True), Industry.id.in_(selected_domain_ids)).all() if selected_domain_ids else []
        profile.domain_links[:] = [VendorOnboardingDomain(industry_id=industry.id) for industry in valid_industries]

        country_name = (request.form.get("country") or "").strip()
        country = CountryMaster.query.filter(CountryMaster.is_active.is_(True), func.lower(CountryMaster.name) == country_name.lower()).first() if country_name else None
        currency_code = (request.form.get("vendor_currency") or "").strip().upper()
        currency = Currency.query.filter(Currency.is_active.is_(True), func.upper(Currency.code) == currency_code).first() if currency_code else None
        if not country:
            flash("Choose a valid country from Country Master.", "danger")
            return redirect(url_for("vendor_portal.onboarding"))
        if not currency:
            flash("Choose a valid currency from Currency Master.", "danger")
            return redirect(url_for("vendor_portal.onboarding"))
        profile.country = country.name
        vendor.currency = currency.code.upper()
        profile.address = (request.form.get("address") or "").strip() or None
        profile.bank_name = (request.form.get("bank_name") or "").strip() or None
        profile.account_holder_name = (request.form.get("account_holder_name") or "").strip() or None
        profile.bank_account_number = (request.form.get("bank_account_number") or "").strip() or None
        profile.ifsc_code = (request.form.get("ifsc_code") or "").strip() or None
        profile.swift_code = (request.form.get("swift_code") or "").strip() or None
        profile.iban = (request.form.get("iban") or "").strip() or None
        profile.paypal_id = (request.form.get("paypal_id") or "").strip() or None
        profile.id_type = (request.form.get("id_type") or "").strip() or None
        profile.id_number = (request.form.get("id_number") or "").strip() or None
        try:
            bank_doc = _save_onboarding_file(request.files.get("bank_document"), vendor.id, "bank")
            id_doc = _save_onboarding_file(request.files.get("id_document"), vendor.id, "identity")
            resume_doc = _save_onboarding_file(request.files.get("resume_document"), vendor.id, "resume")
        except ValueError as exc:
            flash(str(exc), "danger")
            return redirect(url_for("vendor_portal.onboarding"))
        if bank_doc:
            profile.bank_verification_document = bank_doc
        if id_doc:
            profile.id_document = id_doc
        if resume_doc:
            profile.resume_document = resume_doc

        if action == "submit":
            required = [vendor.name, vendor.email, profile.primary_phone, profile.country, profile.address,
                        profile.account_holder_name, (profile.bank_account_number or profile.iban or profile.paypal_id),
                        profile.bank_verification_document, profile.id_type, profile.id_number, profile.id_document]
            if not all(required):
                flash("Complete all required basic, payment and identity fields before submission.", "danger")
                db.session.commit()
                return redirect(url_for("vendor_portal.onboarding"))
            if VendorServiceCapability.query.filter_by(vendor_id=vendor.id).count() == 0:
                flash("Add at least one service before submitting onboarding.", "danger")
                db.session.commit()
                return redirect(url_for("vendor_portal.onboarding"))
            current_nda = _current_nda()
            if current_nda and not _current_nda_signature(vendor, current_nda):
                flash("Please review and digitally sign the current NDA before submitting onboarding.", "danger")
                db.session.commit()
                return redirect(url_for("vendor_portal.onboarding"))
            profile.verification_status = "PENDING"
            profile.submitted_at = _now()
            profile.verification_remark = None
            vendor.onboarding_status = "IN_PROGRESS"
            flash("Onboarding submitted for internal verification.", "success")
        else:
            if profile.verification_status in ("REJECTED", "CHANGES_REQUESTED"):
                profile.verification_status = "DRAFT"
            flash("Onboarding draft saved.", "success")
        db.session.commit()
        return redirect(url_for("vendor_portal.onboarding"))

    services = (
        LeadService.query.join(ServiceSubCategory).join(ServiceCategory)
        .filter(LeadService.is_active.is_(True), ServiceSubCategory.is_active.is_(True), ServiceCategory.is_active.is_(True))
        .order_by(ServiceCategory.sort_order.asc(), ServiceSubCategory.sort_order.asc(), LeadService.sort_order.asc(), LeadService.name.asc()).all()
    )
    service_categories = ServiceCategory.query.filter_by(is_active=True).order_by(ServiceCategory.sort_order.asc(), ServiceCategory.name.asc()).all()
    service_sub_categories = ServiceSubCategory.query.filter_by(is_active=True).order_by(ServiceSubCategory.sort_order.asc(), ServiceSubCategory.name.asc()).all()
    pairs = LanguagePairMaster.query.filter_by(is_active=True).order_by(LanguagePairMaster.id.asc()).all()
    capabilities = VendorServiceCapability.query.filter_by(vendor_id=vendor.id).order_by(VendorServiceCapability.id.desc()).all()
    return render_template(
        "vendor_portal/onboarding.html", vendor=vendor, profile=profile, services=services, service_categories=service_categories,
        service_sub_categories=service_sub_categories, language_pairs=pairs, capabilities=capabilities, units=UNITS, now=_now(),
        countries=_active_countries(), currencies=_active_currencies(),
        native_languages=LanguageMaster.query.filter_by(is_active=True).order_by(LanguageMaster.name.asc()).all(),
        industries=Industry.query.filter_by(is_active=True).order_by(Industry.sort_order.asc(), Industry.name.asc()).all(),
        gender_options=("Male", "Female", "Non-binary", "Prefer not to say", "Other"),
        voice_modulation_options=("Not Applicable", "Neutral / Standard", "Corporate / Narration", "Commercial / Promotional", "E-learning", "Dubbing / Lip-sync", "Character / Animation", "Audiobook / Storytelling", "IVR / Telephony", "Other"),
        current_nda=_current_nda(), nda_signature=_current_nda_signature(vendor),
        onboarding_locked=bool(vendor.onboarding_completed_at or (vendor.onboarding_status or "").upper() == "COMPLETED")
    )


@vendor_portal_bp.route("/onboarding/services/add", methods=["POST"])
@vendor_login_required
def add_onboarding_service():
    vendor = get_current_vendor()
    return_endpoint = "vendor_portal.my_profile" if request.form.get("return_to") == "my_profile" else "vendor_portal.onboarding"
    service_id = request.form.get("service_id", type=int)
    new_service = (request.form.get("new_service") or "").strip()
    if new_service and not service_id:
        db.session.add(VendorServiceRequest(vendor_id=vendor.id, requested_name=new_service))
        db.session.commit()
        flash("New service request submitted to the Vendor Coordinator.", "success")
        return redirect(url_for(return_endpoint))
    service = (LeadService.query.join(ServiceSubCategory).join(ServiceCategory)
               .filter(LeadService.id == service_id, LeadService.is_active.is_(True),
                       ServiceSubCategory.is_active.is_(True), ServiceCategory.is_active.is_(True)).first()) if service_id else None
    if not service:
        flash("Choose a valid active Category, Sub Category and Service, or request a new service.", "danger")
        return redirect(url_for(return_endpoint))

    pair_id = request.form.get("language_pair_id", type=int)
    rate = _safe_decimal(request.form.get("rate"))

    # Keep all values passed to PyMySQL as plain scalar values.  This also
    # protects older vendor records where a currency helper may return a
    # mapping-like value instead of the stored code.
    raw_currency = request.form.get("currency") or vendor.currency or "INR"
    if isinstance(raw_currency, dict):
        raw_currency = raw_currency.get("code") or raw_currency.get("value") or raw_currency.get("name") or "INR"
    currency = str(raw_currency).strip().upper() or "INR"
    currency_master = Currency.query.filter(Currency.is_active.is_(True), func.upper(Currency.code) == currency).first()
    if not currency_master:
        flash("Choose a valid currency from Currency Master.", "danger")
        return redirect(url_for(return_endpoint))
    currency = currency_master.code.upper()

    raw_unit = request.form.get("unit") or "Per Word"
    if isinstance(raw_unit, dict):
        raw_unit = raw_unit.get("value") or raw_unit.get("name") or "Per Word"
    unit = str(raw_unit).strip() or "Per Word"

    capability = VendorServiceCapability(
        vendor_id=int(vendor.id),
        service_id=int(service.id),
        status="DRAFT",
        test_required=True,
    )

    try:
        db.session.add(capability)
        db.session.flush()
        capability_id = int(capability.id)

        if rate > 0:
            vendor_rate = VendorServiceRate(
                capability_id=capability_id,
                language_pair_id=int(pair_id) if pair_id else None,
                rate=Decimal(str(rate)),
                vendor_submitted_rate=Decimal(str(rate)),
                current_offer_rate=Decimal(str(rate)),
                current_offer_by="VENDOR",
                negotiation_status="PENDING_COORDINATOR",
                vendor_accepted_at=_now(),
                currency=currency,
                unit=unit,
            )
            db.session.add(vendor_rate)
            db.session.flush()
            _record_rate_event(vendor_rate, "VENDOR", "SUBMITTED", vendor_rate.current_offer_rate, "Initial rate submitted with service.", vendor_id=vendor.id)
        for sample_file in request.files.getlist("work_samples"):
            saved = _save_work_sample(sample_file, vendor.id, capability_id)
            if saved:
                original_name, sample_path = saved
                db.session.add(VendorServiceWorkSample(capability_id=capability_id, original_filename=original_name, file_path=sample_path))
        db.session.commit()
    except Exception as exc:
        db.session.rollback()
        current_app.logger.exception("Unable to save vendor onboarding service vendor_id=%s service_id=%s", vendor.id, service.id)
        flash("Unable to add the service. Please try again or contact the Vendor Coordinator. {}".format(str(exc)), "danger")
        return redirect(url_for(return_endpoint))

    # AI generation is intentionally a separate transaction.  A test/API
    # failure must never roll back the service/rate that was already saved.
    try:
        pair_names = []
        if pair_id:
            pair = LanguagePairMaster.query.get(pair_id)
            if pair:
                pair_names.append(pair.display_name)
        generated = generate_test(service.name, pair_names)
        test = VendorServiceTest(
            capability_id=capability_id,
            test_code="VT-{:06d}".format(capability_id),
            prompt_text=generated.get("instructions"),
            test_content=generated.get("test_content"),
            rubric=generated.get("rubric"),
            generated_by_ai=True,
            generated_at=_now(),
        )
        db.session.add(test)
        db.session.commit()
        flash("Service added and AI qualification test generated.", "success")
    except Exception as exc:
        db.session.rollback()
        current_app.logger.exception("AI qualification test generation failed capability_id=%s", capability_id)
        try:
            test = VendorServiceTest(
                capability_id=capability_id,
                test_code="VT-{:06d}".format(capability_id),
                generation_error=str(exc),
            )
            db.session.add(test)
            db.session.commit()
        except Exception:
            db.session.rollback()
            current_app.logger.exception("Unable to save AI generation failure capability_id=%s", capability_id)
        flash("Service added, but AI test generation failed. The Vendor Coordinator can regenerate it.", "warning")
    return redirect(url_for(return_endpoint))



def _negotiation_rate_or_404(rate_id, vendor=None):
    rate = VendorServiceRate.query.get_or_404(rate_id)
    if vendor is not None and (not rate.capability or rate.capability.vendor_id != vendor.id):
        abort(404)
    return rate


def _ensure_negotiation_initialized(rate):
    """Make pre-migration / legacy rates participate safely in negotiation."""
    changed = False
    if rate.vendor_submitted_rate is None:
        rate.vendor_submitted_rate = rate.rate or Decimal("0")
        changed = True
    if rate.current_offer_rate is None:
        rate.current_offer_rate = rate.vendor_submitted_rate
        changed = True
    if not rate.current_offer_by:
        rate.current_offer_by = "VENDOR"
        changed = True
    if not rate.negotiation_status:
        rate.negotiation_status = "PENDING_COORDINATOR"
        changed = True
    if not rate.vendor_accepted_at and rate.current_offer_by == "VENDOR" and rate.negotiation_status != "LOCKED":
        rate.vendor_accepted_at = rate.created_at or _now()
        changed = True
    return changed


def _record_rate_event(rate, actor_type, action, offered_rate=None, remarks=None, vendor_id=None, user_id=None):
    db.session.add(VendorRateNegotiationEvent(
        rate_id=rate.id,
        actor_type=actor_type,
        vendor_id=vendor_id,
        user_id=user_id,
        action=action,
        offered_rate=offered_rate,
        remarks=(remarks or "").strip() or None,
    ))


def _lock_rate_if_both_accepted(rate):
    if rate.vendor_accepted_at and rate.coordinator_accepted_at and rate.current_offer_rate is not None:
        now = _now()
        rate.final_rate = rate.current_offer_rate
        rate.rate = rate.current_offer_rate
        rate.negotiation_status = "LOCKED"
        rate.locked_at = now
        _record_rate_event(rate, "SYSTEM", "LOCKED", rate.final_rate, "Both parties accepted the same rate.")
        return True
    return False


@vendor_portal_bp.route("/rate-negotiations")
@vendor_login_required
def rate_negotiations():
    vendor = get_current_vendor()
    rates = (VendorServiceRate.query
             .join(VendorServiceCapability, VendorServiceCapability.id == VendorServiceRate.capability_id)
             .filter(VendorServiceCapability.vendor_id == vendor.id)
             .order_by(VendorServiceRate.locked_at.isnot(None), VendorServiceRate.created_at.desc())
             .all())
    changed = False
    for rate in rates:
        changed = _ensure_negotiation_initialized(rate) or changed
    if changed:
        db.session.commit()
    stats = {
        "total": len(rates),
        "locked": sum(1 for r in rates if r.negotiation_status == "LOCKED"),
        "your_action": sum(1 for r in rates if r.negotiation_status != "LOCKED" and r.current_offer_by == "COORDINATOR"),
        "coordinator_action": sum(1 for r in rates if r.negotiation_status != "LOCKED" and r.current_offer_by == "VENDOR"),
    }
    return render_template("vendor_portal/rate_negotiations.html", vendor=vendor, rates=rates, stats=stats)


@vendor_portal_bp.route("/rate-negotiations/<int:rate_id>/counter", methods=["POST"])
@vendor_login_required
def vendor_counter_rate(rate_id):
    vendor = get_current_vendor()
    rate = _negotiation_rate_or_404(rate_id, vendor)
    _ensure_negotiation_initialized(rate)
    if rate.negotiation_status == "LOCKED":
        flash("This rate is already final and locked.", "warning")
        return redirect(url_for("vendor_portal.rate_negotiations"))
    try:
        new_rate = Decimal((request.form.get("rate") or "").strip())
    except (InvalidOperation, ValueError, TypeError):
        new_rate = Decimal("0")
    if new_rate <= 0:
        flash("Enter a valid rate greater than zero.", "danger")
        return redirect(url_for("vendor_portal.rate_negotiations"))
    remarks = request.form.get("remarks")
    rate.current_offer_rate = new_rate
    rate.current_offer_by = "VENDOR"
    rate.vendor_accepted_at = _now()
    rate.coordinator_accepted_at = None
    rate.negotiation_status = "PENDING_COORDINATOR"
    _record_rate_event(rate, "VENDOR", "COUNTERED", new_rate, remarks, vendor_id=vendor.id)
    db.session.commit()
    flash("Your revised rate has been sent to the Vendor Coordinator.", "success")
    return redirect(url_for("vendor_portal.rate_negotiations"))


@vendor_portal_bp.route("/rate-negotiations/<int:rate_id>/accept", methods=["POST"])
@vendor_login_required
def vendor_accept_rate(rate_id):
    vendor = get_current_vendor()
    rate = _negotiation_rate_or_404(rate_id, vendor)
    _ensure_negotiation_initialized(rate)
    if rate.negotiation_status == "LOCKED":
        flash("This rate is already final and locked.", "info")
        return redirect(url_for("vendor_portal.rate_negotiations"))
    if rate.current_offer_by != "COORDINATOR":
        flash("Your latest offer is awaiting the Vendor Coordinator. You cannot accept your own offer.", "warning")
        return redirect(url_for("vendor_portal.rate_negotiations"))
    rate.vendor_accepted_at = _now()
    _record_rate_event(rate, "VENDOR", "ACCEPTED", rate.current_offer_rate, request.form.get("remarks"), vendor_id=vendor.id)
    locked = _lock_rate_if_both_accepted(rate)
    if not locked:
        rate.negotiation_status = "PENDING_COORDINATOR"
    db.session.commit()
    flash("Rate accepted and locked as the final agreed rate." if locked else "Rate accepted.", "success")
    return redirect(url_for("vendor_portal.rate_negotiations"))


@vendor_admin_bp.route("/rate-negotiations")
@login_required
@require_perm("vendor_onboarding.manage")
def coordinator_rate_negotiations():
    q = (request.args.get("q") or "").strip()
    status = (request.args.get("status") or "open").strip().lower()
    query = (VendorServiceRate.query
             .join(VendorServiceCapability, VendorServiceCapability.id == VendorServiceRate.capability_id)
             .join(VendorMaster, VendorMaster.id == VendorServiceCapability.vendor_id)
             .join(LeadService, LeadService.id == VendorServiceCapability.service_id))
    if q:
        like = "%{}%".format(q)
        query = query.filter(or_(VendorMaster.name.ilike(like), VendorMaster.external_translator_id.ilike(like), LeadService.name.ilike(like)))
    if status == "open":
        query = query.filter(VendorServiceRate.negotiation_status != "LOCKED")
    elif status == "locked":
        query = query.filter(VendorServiceRate.negotiation_status == "LOCKED")
    elif status == "my_action":
        query = query.filter(VendorServiceRate.negotiation_status != "LOCKED", VendorServiceRate.current_offer_by == "VENDOR")
    elif status == "vendor_action":
        query = query.filter(VendorServiceRate.negotiation_status != "LOCKED", VendorServiceRate.current_offer_by == "COORDINATOR")
    rates = query.order_by(VendorServiceRate.locked_at.isnot(None), VendorServiceRate.updated_at.desc()).limit(1000).all()
    changed = False
    for rate in rates:
        changed = _ensure_negotiation_initialized(rate) or changed
    if changed:
        db.session.commit()
    all_rates = VendorServiceRate.query.all()
    stats = {
        "open": sum(1 for r in all_rates if (r.negotiation_status or "PENDING_COORDINATOR") != "LOCKED"),
        "my_action": sum(1 for r in all_rates if (r.negotiation_status or "PENDING_COORDINATOR") != "LOCKED" and (r.current_offer_by or "VENDOR") == "VENDOR"),
        "vendor_action": sum(1 for r in all_rates if (r.negotiation_status or "PENDING_COORDINATOR") != "LOCKED" and r.current_offer_by == "COORDINATOR"),
        "locked": sum(1 for r in all_rates if r.negotiation_status == "LOCKED"),
    }
    return render_template("vendor_admin/rate_negotiations.html", rates=rates, stats=stats, q=q, status=status)


@vendor_admin_bp.route("/rate-negotiations/<int:rate_id>/counter", methods=["POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def coordinator_counter_rate(rate_id):
    rate = _negotiation_rate_or_404(rate_id)
    _ensure_negotiation_initialized(rate)
    if rate.negotiation_status == "LOCKED":
        flash("This rate is already final and locked.", "warning")
        return redirect(url_for("vendor_admin.coordinator_rate_negotiations"))
    try:
        new_rate = Decimal((request.form.get("rate") or "").strip())
    except (InvalidOperation, ValueError, TypeError):
        new_rate = Decimal("0")
    if new_rate <= 0:
        flash("Enter a valid rate greater than zero.", "danger")
        return redirect(url_for("vendor_admin.coordinator_rate_negotiations"))
    rate.current_offer_rate = new_rate
    rate.current_offer_by = "COORDINATOR"
    rate.coordinator_accepted_at = _now()
    rate.vendor_accepted_at = None
    rate.negotiation_status = "PENDING_VENDOR"
    _record_rate_event(rate, "COORDINATOR", "COUNTERED", new_rate, request.form.get("remarks"), user_id=current_user.id)
    db.session.commit()
    flash("Counter-offer sent to the vendor.", "success")
    return redirect(url_for("vendor_admin.coordinator_rate_negotiations"))


@vendor_admin_bp.route("/rate-negotiations/<int:rate_id>/accept", methods=["POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def coordinator_accept_rate(rate_id):
    rate = _negotiation_rate_or_404(rate_id)
    _ensure_negotiation_initialized(rate)
    if rate.negotiation_status == "LOCKED":
        flash("This rate is already final and locked.", "info")
        return redirect(url_for("vendor_admin.coordinator_rate_negotiations"))
    if rate.current_offer_by != "VENDOR":
        flash("Your latest counter-offer is awaiting the vendor. You cannot accept your own offer.", "warning")
        return redirect(url_for("vendor_admin.coordinator_rate_negotiations"))
    rate.coordinator_accepted_at = _now()
    _record_rate_event(rate, "COORDINATOR", "ACCEPTED", rate.current_offer_rate, request.form.get("remarks"), user_id=current_user.id)
    locked = _lock_rate_if_both_accepted(rate)
    if not locked:
        rate.negotiation_status = "PENDING_VENDOR"
    db.session.commit()
    flash("Rate accepted and locked as the final agreed rate." if locked else "Rate accepted.", "success")
    return redirect(url_for("vendor_admin.coordinator_rate_negotiations"))


@vendor_portal_bp.route("/onboarding/nda/sign", methods=["POST"])
@vendor_login_required
def sign_nda():
    vendor = get_current_vendor()
    return_endpoint = "vendor_portal.my_profile" if request.form.get("return_to") == "my_profile" else "vendor_portal.onboarding"
    nda = _current_nda()
    if not nda:
        flash("There is no active NDA available for signature.", "warning")
        return redirect(url_for(return_endpoint))
    existing = VendorNDASignature.query.filter_by(vendor_id=vendor.id, nda_document_id=nda.id).first()
    if existing and existing.expires_at >= _now():
        flash("The current NDA is already signed.", "info")
        return redirect(url_for(return_endpoint))
    signer_name = (request.form.get("signer_name") or "").strip()
    consent = request.form.get("nda_consent") == "1"
    if not signer_name or not consent:
        flash("Enter your full legal name and confirm your agreement before signing the NDA.", "danger")
        return redirect(url_for(return_endpoint))
    if signer_name.lower() != (vendor.name or "").strip().lower():
        flash("The digital signature name must match the vendor name on your profile.", "danger")
        return redirect(url_for(return_endpoint))
    now = _now()
    annual_expiry = now + timedelta(days=365)
    expires_at = nda.effective_to if nda.effective_to < annual_expiry else annual_expiry
    consent_text = "I have read and agree to the NDA version {} and intend this typed name to constitute my electronic signature.".format(nda.version)
    signature = existing or VendorNDASignature(vendor_id=vendor.id, nda_document_id=nda.id)
    signature.signer_name = signer_name
    signature.consent_text = consent_text
    signature.signed_at = now
    signature.expires_at = expires_at
    signature.ip_address = (request.headers.get("X-Forwarded-For") or request.remote_addr or "")[:100]
    signature.user_agent = (request.headers.get("User-Agent") or "")[:500]
    signature.document_sha256 = nda.file_sha256
    if not existing:
        db.session.add(signature)
    _recalculate_onboarding(vendor)
    db.session.commit()
    log_audit("VendorNDASignature", signature.id, "SIGNED", new="Vendor signed NDA version {}".format(nda.version))
    flash("NDA digitally signed successfully.", "success")
    return redirect(url_for(return_endpoint))


@vendor_portal_bp.route("/onboarding/services/<int:capability_id>/work-samples", methods=["POST"])
@vendor_login_required
def upload_work_samples(capability_id):
    vendor = get_current_vendor()
    return_endpoint = "vendor_portal.my_profile" if request.form.get("return_to") == "my_profile" else "vendor_portal.onboarding"
    capability = VendorServiceCapability.query.get_or_404(capability_id)
    if capability.vendor_id != vendor.id:
        abort(403)
    files = [f for f in request.files.getlist("work_samples") if f and f.filename]
    if not files:
        flash("Choose at least one work sample to upload.", "warning")
        return redirect(url_for(return_endpoint))
    try:
        count = 0
        for sample_file in files:
            saved = _save_work_sample(sample_file, vendor.id, capability.id)
            if saved:
                original_name, sample_path = saved
                db.session.add(VendorServiceWorkSample(capability_id=capability.id, original_filename=original_name, file_path=sample_path))
                count += 1
        db.session.commit()
        flash("{} work sample{} uploaded.".format(count, "" if count == 1 else "s"), "success")
    except ValueError as exc:
        db.session.rollback()
        flash(str(exc), "danger")
    return redirect(url_for(return_endpoint))


@vendor_portal_bp.route("/onboarding/tests/<int:test_id>/submit", methods=["POST"])
@vendor_login_required
def submit_onboarding_test(test_id):
    vendor = get_current_vendor()
    return_endpoint = "vendor_portal.my_profile" if request.form.get("return_to") == "my_profile" else "vendor_portal.onboarding"
    test = VendorServiceTest.query.get_or_404(test_id)
    if test.capability.vendor_id != vendor.id:
        abort(403)
    answer = (request.form.get("answer") or "").strip()
    if not answer:
        flash("Enter your completed test response before submitting.", "danger")
        return redirect(url_for(return_endpoint))
    test.vendor_answer = answer
    test.submitted_at = _now()
    test.capability.status = "TEST_SUBMITTED"
    db.session.commit()
    try:
        result = score_test(test.capability.service.name, test.test_content or "", test.rubric or "", answer)
        test.ai_score = max(0, min(100, _safe_decimal(result.get("score"))))
        test.ai_feedback = result.get("feedback") or ""
        test.ai_scored_at = _now()
        test.capability.status = "AI_REVIEWED"
        db.session.commit()
    except Exception:
        # AI scoring is an internal review step. The translator's submission
        # remains valid even if scoring fails, so never expose provider/API
        # details to the translator. Coordinators can review it manually.
        db.session.rollback()
        current_app.logger.exception("AI qualification scoring failed test_id=%s", test_id)

    flash("Test submitted successfully.", "success")
    return redirect(url_for(return_endpoint))


@vendor_portal_bp.route("/peer-reviews")
@vendor_login_required
def peer_reviews():
    vendor = get_current_vendor()
    tests = VendorServiceTest.query.filter_by(peer_reviewer_vendor_id=vendor.id).order_by(VendorServiceTest.peer_assigned_at.desc()).all()
    return render_template("vendor_portal/peer_reviews.html", tests=tests)


@vendor_portal_bp.route("/peer-reviews/<int:test_id>", methods=["GET", "POST"])
@vendor_login_required
def peer_review_test(test_id):
    vendor = get_current_vendor()
    test = VendorServiceTest.query.get_or_404(test_id)
    if test.peer_reviewer_vendor_id != vendor.id or test.capability.vendor_id == vendor.id:
        abort(403)
    if request.method == "POST":
        score = _safe_decimal(request.form.get("score"))
        feedback = (request.form.get("feedback") or "").strip()
        if score < 0 or score > 100:
            flash("Peer score must be between 0 and 100.", "danger")
        else:
            test.peer_score = score
            test.peer_feedback = feedback
            test.peer_reviewed_at = _now()
            test.capability.status = "PEER_REVIEWED"
            db.session.commit()
            flash("Anonymous peer review submitted.", "success")
            return redirect(url_for("vendor_portal.peer_reviews"))
    return render_template("vendor_portal/peer_review_test.html", test=test)


@vendor_admin_bp.route("/onboarding/nda", methods=["GET", "POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def nda_management():
    if request.method == "POST":
        title = (request.form.get("title") or "Vendor NDA").strip()
        version = (request.form.get("version") or "").strip()
        file_obj = request.files.get("nda_file")
        effective_from_text = (request.form.get("effective_from") or "").strip()
        effective_to_text = (request.form.get("effective_to") or "").strip()
        if not version or not file_obj or not file_obj.filename:
            flash("NDA version and PDF document are required.", "danger")
            return redirect(url_for("vendor_admin.nda_management"))
        ext = os.path.splitext(secure_filename(file_obj.filename))[1].lower()
        if ext != ".pdf":
            flash("Upload the NDA as a PDF document.", "danger")
            return redirect(url_for("vendor_admin.nda_management"))
        try:
            effective_from = datetime.strptime(effective_from_text, "%Y-%m-%d") if effective_from_text else _now()
            effective_to = datetime.strptime(effective_to_text, "%Y-%m-%d") if effective_to_text else effective_from + timedelta(days=365)
        except ValueError:
            flash("Enter valid NDA effective dates.", "danger")
            return redirect(url_for("vendor_admin.nda_management"))
        if effective_to <= effective_from:
            flash("NDA expiry must be after the effective date.", "danger")
            return redirect(url_for("vendor_admin.nda_management"))
        root = os.path.join(current_app.root_path, "static", "uploads", "vendor_onboarding", "nda")
        os.makedirs(root, exist_ok=True)
        stored = "nda_{}_{}_{}.pdf".format(secure_filename(version), _now().strftime("%Y%m%d%H%M%S"), secrets.token_hex(4))
        absolute_path = os.path.join(root, stored)
        file_obj.save(absolute_path)
        file_path = "uploads/vendor_onboarding/nda/{}".format(stored)
        # A newly uploaded annual NDA becomes the active version. Previous
        # versions remain in the audit history but no longer require signature.
        VendorNDADocument.query.update({VendorNDADocument.is_active: False}, synchronize_session=False)
        nda = VendorNDADocument(
            title=title,
            version=version,
            file_path=file_path,
            file_sha256=_file_sha256(absolute_path),
            effective_from=effective_from,
            effective_to=effective_to,
            is_active=True,
            uploaded_by_id=current_user.id,
        )
        db.session.add(nda)
        db.session.commit()
        flash("Annual NDA uploaded and activated. Vendors will be asked to digitally sign this version.", "success")
        return redirect(url_for("vendor_admin.nda_management"))
    documents = VendorNDADocument.query.order_by(VendorNDADocument.id.desc()).all()
    current = _current_nda()
    return render_template("vendor_admin/nda_management.html", documents=documents, current_nda=current, now=_now())


@vendor_admin_bp.route("/onboarding")
@login_required
@require_perm("vendor_onboarding.view")
def onboarding_dashboard():
    q = (request.args.get("q") or "").strip()
    view = (request.args.get("view") or "action").strip().lower()
    valid_views = {"action", "verification", "tests", "overdue", "completed", "all"}
    if view not in valid_views:
        view = "action"

    query = VendorMaster.query
    if q:
        like = "%{}%".format(q)
        query = query.filter(or_(VendorMaster.name.ilike(like), VendorMaster.email.ilike(like), VendorMaster.external_translator_id.ilike(like)))

    # Keep dashboard states tied to the same definitions used by the KPI cards.
    if view == "verification":
        query = query.join(VendorOnboardingProfile, VendorOnboardingProfile.vendor_id == VendorMaster.id).filter(VendorOnboardingProfile.verification_status == "PENDING")
    elif view == "tests":
        query = query.join(VendorServiceCapability, VendorServiceCapability.vendor_id == VendorMaster.id).join(VendorServiceTest, VendorServiceTest.capability_id == VendorServiceCapability.id).filter(VendorServiceTest.submitted_at.isnot(None), VendorServiceTest.coordinator_reviewed_at.is_(None)).distinct()
    elif view == "overdue":
        query = query.filter(VendorMaster.onboarding_status != "COMPLETED", VendorMaster.onboarding_due_at.isnot(None), VendorMaster.onboarding_due_at < _now())
    elif view == "completed":
        query = query.filter(VendorMaster.onboarding_status == "COMPLETED")
    elif view == "action":
        pending_verification = db.session.query(VendorOnboardingProfile.vendor_id).filter(VendorOnboardingProfile.verification_status == "PENDING")
        pending_test = db.session.query(VendorServiceCapability.vendor_id).join(VendorServiceTest, VendorServiceTest.capability_id == VendorServiceCapability.id).filter(VendorServiceTest.submitted_at.isnot(None), VendorServiceTest.coordinator_reviewed_at.is_(None))
        query = query.filter(or_(VendorMaster.id.in_(pending_verification), VendorMaster.id.in_(pending_test), and_(VendorMaster.onboarding_status != "COMPLETED", VendorMaster.onboarding_due_at.isnot(None), VendorMaster.onboarding_due_at < _now())))

    vendors = query.order_by(VendorMaster.onboarding_due_at.asc(), VendorMaster.name.asc()).limit(500).all()
    stats = {
        "pending": VendorMaster.query.filter(VendorMaster.onboarding_status != "COMPLETED").count(),
        "completed": VendorMaster.query.filter_by(onboarding_status="COMPLETED").count(),
        "verification": VendorOnboardingProfile.query.filter_by(verification_status="PENDING").count(),
        "tests": VendorServiceTest.query.filter(VendorServiceTest.submitted_at.isnot(None), VendorServiceTest.coordinator_reviewed_at.is_(None)).count(),
        "overdue": VendorMaster.query.filter(VendorMaster.onboarding_status != "COMPLETED", VendorMaster.onboarding_due_at.isnot(None), VendorMaster.onboarding_due_at < _now()).count(),
    }
    stats["action"] = db.session.query(VendorMaster.id).filter(or_(
        VendorMaster.id.in_(db.session.query(VendorOnboardingProfile.vendor_id).filter(VendorOnboardingProfile.verification_status == "PENDING")),
        VendorMaster.id.in_(db.session.query(VendorServiceCapability.vendor_id).join(VendorServiceTest, VendorServiceTest.capability_id == VendorServiceCapability.id).filter(VendorServiceTest.submitted_at.isnot(None), VendorServiceTest.coordinator_reviewed_at.is_(None))),
        and_(VendorMaster.onboarding_status != "COMPLETED", VendorMaster.onboarding_due_at.isnot(None), VendorMaster.onboarding_due_at < _now())
    )).count()

    rows = []
    for vendor in vendors:
        profile = vendor.onboarding_profile
        verification_pending = bool(profile and profile.verification_status == "PENDING")
        tests_pending = VendorServiceTest.query.join(VendorServiceCapability).filter(VendorServiceCapability.vendor_id == vendor.id, VendorServiceTest.submitted_at.isnot(None), VendorServiceTest.coordinator_reviewed_at.is_(None)).count()
        overdue = bool(vendor.onboarding_status != "COMPLETED" and vendor.onboarding_due_at and vendor.onboarding_due_at < _now())
        if verification_pending:
            next_action, action_class = "Verify documents", "warning"
        elif tests_pending:
            next_action, action_class = "Score {} test{}".format(tests_pending, "" if tests_pending == 1 else "s"), "primary"
        elif overdue:
            next_action, action_class = "Review overdue", "danger"
        elif vendor.onboarding_status == "COMPLETED":
            next_action, action_class = "Completed", "success"
        else:
            next_action, action_class = "Waiting on vendor", "secondary"
        rows.append({"vendor": vendor, "verification_pending": verification_pending, "tests_pending": tests_pending, "overdue": overdue, "next_action": next_action, "action_class": action_class})

    service_requests = VendorServiceRequest.query.filter_by(status="PENDING").order_by(VendorServiceRequest.created_at.asc()).all()
    services = LeadService.query.filter_by(is_active=True).order_by(LeadService.name.asc()).all()
    return render_template("vendor_admin/onboarding_dashboard.html", rows=rows, stats=stats, q=q, view=view, now=_now(), service_requests=service_requests, services=services)


@vendor_admin_bp.route("/onboarding/<int:vendor_id>")
@login_required
@require_perm("vendor_onboarding.view")
def onboarding_review(vendor_id):
    vendor = VendorMaster.query.get_or_404(vendor_id)
    profile = _profile(vendor)
    capabilities = VendorServiceCapability.query.filter_by(vendor_id=vendor.id).order_by(VendorServiceCapability.id.desc()).all()
    reviewers = VendorMaster.query.filter(VendorMaster.id != vendor.id, VendorMaster.portal_active.is_(True), VendorMaster.is_active.is_(True)).order_by(VendorMaster.name.asc()).all()
    current_nda = _current_nda()
    nda_signature = _current_nda_signature(vendor, current_nda)
    return render_template("vendor_admin/onboarding_review.html", vendor=vendor, profile=profile, billing_profile=vendor.billing_profile, capabilities=capabilities, reviewers=reviewers, now=_now(), current_nda=current_nda, nda_signature=nda_signature)


@vendor_admin_bp.route("/onboarding/<int:vendor_id>/verify-basic", methods=["POST"])
@login_required
@require_perm("vendor_onboarding.verify")
def verify_basic(vendor_id):
    vendor = VendorMaster.query.get_or_404(vendor_id)
    profile = _profile(vendor)
    if profile.verification_status == "APPROVED":
        flash("Basic/compliance verification is already approved.", "info")
        return redirect(url_for("vendor_admin.onboarding_review", vendor_id=vendor.id))
    action = (request.form.get("action") or "").upper()
    remark = (request.form.get("remark") or "").strip()
    if action not in ("APPROVED", "REJECTED", "CHANGES_REQUESTED"):
        abort(400)
    profile.verification_status = action
    profile.verification_remark = remark or None
    profile.verified_by_id = current_user.id
    profile.verified_at = _now() if action == "APPROVED" else None
    if action == "APPROVED":
        _sync_approved_onboarding_to_billing(vendor, profile)
    _recalculate_onboarding(vendor)
    db.session.commit()
    flash("Basic/compliance verification updated.", "success")
    return redirect(url_for("vendor_admin.onboarding_review", vendor_id=vendor.id))


@vendor_admin_bp.route("/onboarding/tests/<int:test_id>/regenerate", methods=["POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def regenerate_test(test_id):
    test = VendorServiceTest.query.get_or_404(test_id)
    capability = test.capability
    pair_names = [rate.language_pair.display_name for rate in capability.rates.all() if rate.language_pair]
    try:
        generated = generate_test(capability.service.name, pair_names)
        test.prompt_text = generated.get("instructions")
        test.test_content = generated.get("test_content")
        test.rubric = generated.get("rubric")
        test.generated_by_ai = True
        test.generation_error = None
        test.generated_at = _now()
        db.session.commit()
        flash("AI test regenerated.", "success")
    except Exception as exc:
        test.generation_error = str(exc)
        db.session.commit()
        flash("AI test generation failed: {}".format(str(exc)), "danger")
    return redirect(url_for("vendor_admin.onboarding_review", vendor_id=capability.vendor_id))


@vendor_admin_bp.route("/onboarding/tests/<int:test_id>/assign-peer", methods=["POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def assign_peer(test_id):
    test = VendorServiceTest.query.get_or_404(test_id)
    reviewer_id = request.form.get("reviewer_vendor_id", type=int)
    reviewer = VendorMaster.query.get(reviewer_id) if reviewer_id else None
    if not reviewer or reviewer.id == test.capability.vendor_id:
        flash("Choose a different active translator for peer review.", "danger")
    else:
        test.peer_reviewer_vendor_id = reviewer.id
        test.peer_assigned_at = _now()
        test.capability.peer_review_required = True
        test.capability.status = "PEER_ASSIGNED"
        db.session.commit()
        flash("Anonymous peer review assigned.", "success")
    return redirect(url_for("vendor_admin.onboarding_review", vendor_id=test.capability.vendor_id))


@vendor_admin_bp.route("/onboarding/tests/<int:test_id>/coordinator-score", methods=["POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def coordinator_score(test_id):
    test = VendorServiceTest.query.get_or_404(test_id)
    capability = test.capability
    if test.coordinator_reviewed_at or capability.status == "APPROVED":
        flash("This service has already been finally scored and approved.", "info")
        return redirect(url_for("vendor_admin.onboarding_review", vendor_id=capability.vendor_id))
    score = _safe_decimal(request.form.get("score"))
    level = request.form.get("level", type=int)
    feedback = (request.form.get("feedback") or "").strip()
    if score < 0 or score > 100 or level not in (1, 2, 3, 4, 5):
        flash("Coordinator score must be 0-100 and level must be 1-5.", "danger")
    else:
        test.coordinator_score = score
        test.coordinator_feedback = feedback
        test.coordinator_reviewed_at = _now()
        test.coordinator_reviewed_by_id = current_user.id
        capability.coordinator_score = score
        capability.coordinator_remark = feedback
        capability.final_level = level
        capability.status = "APPROVED"
        capability.approved_at = _now()
        capability.approved_by_id = current_user.id
        _recalculate_onboarding(capability.vendor)
        db.session.commit()
        flash("Service approved at Level {}.".format(level), "success")
    return redirect(url_for("vendor_admin.onboarding_review", vendor_id=capability.vendor_id))


@vendor_admin_bp.route("/onboarding/otp")
@login_required
@require_perm("vendor_onboarding.view_otp")
def otp_status():
    rows = VendorEmailOTP.query.order_by(VendorEmailOTP.created_at.desc()).limit(300).all()
    return render_template("vendor_admin/otp_status.html", rows=rows, now=_now())


@vendor_admin_bp.route("/onboarding/otp/<int:vendor_id>/resend", methods=["POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def admin_resend_otp(vendor_id):
    vendor = VendorMaster.query.get_or_404(vendor_id)
    if not vendor.email:
        flash("Vendor has no email address.", "danger")
    else:
        _send_otp(vendor)
        flash("New OTP generated and email attempted.", "success")
    return redirect(url_for("vendor_admin.otp_status"))


@vendor_admin_bp.route("/translators/<int:vendor_id>/status", methods=["POST"])
@login_required
@require_perm("vendor_status.manage")
def update_translator_status(vendor_id):
    vendor = VendorMaster.query.get_or_404(vendor_id)
    new_status = (request.form.get("translator_status") or "").strip().upper()
    reason = (request.form.get("reason") or "").strip()
    remark = (request.form.get("remark") or "").strip()
    if new_status not in STATUS_OPTIONS or not reason:
        flash("Choose a valid translator status and provide a reason.", "danger")
        return redirect(request.referrer or url_for("vendor_admin.translator_detail", vendor_id=vendor.id))
    old_status = vendor.translator_status or "ACTIVE"
    vendor.translator_status = new_status
    db.session.add(VendorStatusHistory(vendor_id=vendor.id, old_status=old_status, new_status=new_status, reason=reason, remark=remark or None, changed_by_id=current_user.id))
    db.session.commit()
    log_audit("VendorMaster", vendor.id, "UPDATE", "translator_status", old_status, new_status)
    flash("Translator status updated to {}.".format(new_status.replace("_", " ").title()), "success")
    return redirect(request.referrer or url_for("vendor_admin.translator_detail", vendor_id=vendor.id))

@vendor_admin_bp.route("/onboarding/languages", methods=["GET", "POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def language_pairs():
    if request.method == "POST":
        action = request.form.get("action") or "language"
        if action == "language":
            name = (request.form.get("name") or "").strip()
            code = (request.form.get("code") or "").strip() or None
            if not name:
                flash("Language name is required.", "danger")
            elif LanguageMaster.query.filter(func.lower(LanguageMaster.name) == name.lower()).first():
                flash("That language already exists.", "warning")
            else:
                db.session.add(LanguageMaster(name=name, code=code, is_active=True))
                db.session.commit()
                flash("Language added.", "success")
        elif action == "pair":
            source_id = request.form.get("source_language_id", type=int)
            target_id = request.form.get("target_language_id", type=int)
            if not source_id or not target_id or source_id == target_id:
                flash("Choose two different languages.", "danger")
            elif LanguagePairMaster.query.filter_by(source_language_id=source_id, target_language_id=target_id).first():
                flash("That directional language pair already exists.", "warning")
            else:
                db.session.add(LanguagePairMaster(source_language_id=source_id, target_language_id=target_id, is_active=True))
                db.session.commit()
                flash("Language pair added.", "success")
        return redirect(url_for("vendor_admin.language_pairs"))
    languages = LanguageMaster.query.order_by(LanguageMaster.name.asc()).all()
    pairs = LanguagePairMaster.query.order_by(LanguagePairMaster.id.desc()).all()
    return render_template("vendor_admin/language_pairs.html", languages=languages, pairs=pairs)


@vendor_admin_bp.route("/onboarding/service-requests/<int:request_id>/approve", methods=["POST"])
@login_required
@require_perm("vendor_onboarding.manage")
def approve_service_request(request_id):
    item = VendorServiceRequest.query.get_or_404(request_id)
    service_id = request.form.get("service_id", type=int)
    create_new = request.form.get("create_new") == "1"
    service = LeadService.query.get(service_id) if service_id else None
    if create_new and not service:
        existing = LeadService.query.filter(func.lower(LeadService.name) == item.requested_name.lower()).first()
        if existing:
            service = existing
        else:
            fallback_category = ServiceCategory.query.filter(func.lower(ServiceCategory.name) == "uncategorised").first()
            if not fallback_category:
                fallback_category = ServiceCategory(name="Uncategorised", description="Temporary category for services awaiting classification", is_active=True, sort_order=9999)
                db.session.add(fallback_category)
                db.session.flush()
            fallback_sub = ServiceSubCategory.query.filter(ServiceSubCategory.category_id == fallback_category.id, func.lower(ServiceSubCategory.name) == "general").first()
            if not fallback_sub:
                fallback_sub = ServiceSubCategory(category_id=fallback_category.id, name="General", description="Temporary sub category for services awaiting classification", is_active=True, sort_order=9999)
                db.session.add(fallback_sub)
                db.session.flush()
            service = LeadService(name=item.requested_name, sub_category_id=fallback_sub.id, is_active=True)
            db.session.add(service)
            db.session.flush()
    if not service:
        flash("Choose an existing service or create the requested service.", "danger")
        return redirect(url_for("vendor_admin.onboarding_dashboard"))
    item.status = "APPROVED"
    item.mapped_service_id = service.id
    item.reviewed_at = _now()
    item.reviewed_by_id = current_user.id
    capability = VendorServiceCapability(vendor_id=item.vendor_id, service_id=service.id, status="DRAFT", test_required=True)
    db.session.add(capability)
    db.session.flush()
    db.session.add(VendorServiceTest(capability_id=capability.id, test_code="VT-{:06d}".format(capability.id)))
    db.session.commit()
    flash("Service request approved. The capability has been added; generate its AI test from the review page.", "success")
    return redirect(url_for("vendor_admin.onboarding_review", vendor_id=item.vendor_id))


@vendor_finance_bp.route("/vendor-status")
@login_required
@require_perm("vendor_status.manage")
def vendor_status_management():
    q = (request.args.get("q") or "").strip()
    status_filter = (request.args.get("status") or "").strip().upper()
    onboarding_filter = (request.args.get("onboarding") or "").strip().upper()
    eligibility_filter = (request.args.get("eligibility") or "").strip().lower()
    query = VendorMaster.query
    if q:
        like = "%{}%".format(q)
        query = query.filter(or_(VendorMaster.name.ilike(like), VendorMaster.email.ilike(like), VendorMaster.external_translator_id.ilike(like)))
    if status_filter in STATUS_OPTIONS:
        query = query.filter(func.upper(VendorMaster.translator_status) == status_filter)
    if onboarding_filter in ("NOT_STARTED", "IN_PROGRESS", "COMPLETED", "EXEMPT"):
        query = query.filter(func.upper(VendorMaster.onboarding_status) == onboarding_filter)
    candidates = query.order_by(VendorMaster.name.asc()).limit(1000).all()
    rows = []
    for vendor in candidates:
        allowed, reason = vendor.assignment_eligibility(_now())
        if eligibility_filter == "eligible" and not allowed:
            continue
        if eligibility_filter == "blocked" and allowed:
            continue
        rows.append({"vendor": vendor, "allowed": allowed, "reason": reason})
        if len(rows) >= 500:
            break
    all_vendors = VendorMaster.query.all()
    stats = {
        "total": len(all_vendors),
        "active": sum(1 for v in all_vendors if (v.translator_status or "ACTIVE").upper() == "ACTIVE"),
        "blocked": sum(1 for v in all_vendors if not v.assignment_eligibility(_now())[0]),
        "completed": sum(1 for v in all_vendors if (v.onboarding_status or "").upper() in ("COMPLETED", "EXEMPT")),
    }
    return render_template(
        "vendor_finance/vendor_status.html", rows=rows, q=q, now=_now(), statuses=STATUS_OPTIONS, stats=stats,
        status_filter=status_filter, onboarding_filter=onboarding_filter, eligibility_filter=eligibility_filter
    )
