from datetime import date, datetime, timedelta
from functools import wraps
from decimal import Decimal
from io import BytesIO
import hashlib
import json
import os
import re
import uuid

from flask import (
    abort,
    current_app,
    flash,
    redirect,
    render_template,
    request,
    send_file,
    session,
    url_for,
)
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
from sqlalchemy import func, or_
from werkzeug.utils import secure_filename

from app import db
from app.mail_utils import send_vendor_password_reset_email
from app.models import (
    OperationsChecklistQuestion,
    OperationsChecklistResponse,
    OperationsJobcardAssignment,
    OperationsJobcardFieldValue,
    OperationsJobcardService,
    Invoice,
    VendorInvoice,
    VendorInvoiceItem,
    VendorMaster,
    VendorBillingProfile,
    VendorOnboardingProfile,
    VendorOnboardingDomain,
    VendorNDADocument,
    VendorNDASignature,
    VendorEmailOTP,
    VendorPrivacyEvent,
    VendorPrivacyTombstone,
    VendorServiceCapability,
    VendorServiceRequest,
    VendorServiceTest,
    VendorServiceWorkSample,
    LeadService,
    ServiceCategory,
    ServiceSubCategory,
    LanguagePairMaster,
    LanguageMaster,
    Industry,
    CountryMaster,
    Currency,
    XbenchReport,
)
from . import vendor_portal_bp
from .invoice_pdf import generate_system_vendor_invoice_pdf


VENDOR_SESSION_KEY = "vendor_portal_vendor_id"
MAX_FAILED_LOGINS = 5
LOCK_MINUTES = 15
RESET_TOKEN_MAX_AGE = 60 * 60
PRIVACY_NOTICE_VERSION = "2026-09-03"

# Keep this deliberately broad because translation work may include
# documents, DTP packages, subtitles, archives, images and spreadsheets.
ALLOWED_VENDOR_UPLOAD_EXTENSIONS = {
    ".zip", ".rar", ".7z",
    ".doc", ".docx", ".rtf", ".txt", ".pdf",
    ".xls", ".xlsx", ".csv",
    ".ppt", ".pptx",
    ".xml", ".json", ".html", ".htm",
    ".srt", ".vtt", ".ass",
    ".idml", ".indd",
    ".jpg", ".jpeg", ".png", ".tif", ".tiff",
}


def _now():
    return datetime.utcnow()


def _serializer():
    secret = current_app.config.get("SECRET_KEY")
    if not secret:
        raise RuntimeError(
            "SECRET_KEY is required for Vendor Portal password reset links."
        )
    return URLSafeTimedSerializer(
        secret,
        salt="crystal-nexus-vendor-password-reset",
    )


def _password_fingerprint(vendor):
    raw = vendor.portal_password_hash or "NO_PASSWORD"
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:24]


def generate_vendor_reset_token(vendor):
    return _serializer().dumps({
        "vendor_id": vendor.id,
        "fp": _password_fingerprint(vendor),
    })


def verify_vendor_reset_token(token):
    try:
        data = _serializer().loads(token, max_age=RESET_TOKEN_MAX_AGE)
    except (SignatureExpired, BadSignature):
        return None

    vendor = db.session.get(VendorMaster, data.get("vendor_id"))
    if not vendor:
        return None

    if data.get("fp") != _password_fingerprint(vendor):
        return None

    return vendor


def get_current_vendor():
    vendor_id = session.get(VENDOR_SESSION_KEY)

    if not vendor_id:
        return None

    try:
        vendor_id = int(vendor_id)
    except (TypeError, ValueError):
        session.pop(VENDOR_SESSION_KEY, None)
        return None

    vendor = db.session.get(VendorMaster, vendor_id)

    if not vendor or not vendor.can_login_to_portal():
        session.pop(VENDOR_SESSION_KEY, None)
        return None

    return vendor


def vendor_login_required(view_func):
    @wraps(view_func)
    def wrapped(*args, **kwargs):
        vendor = get_current_vendor()

        if vendor is None:
            next_url = (
                request.full_path
                if request.query_string
                else request.path
            )
            return redirect(
                url_for("vendor_portal.login", next=next_url)
            )

        return view_func(*args, **kwargs)

    return wrapped


def _safe_next_url(value):
    value = (value or "").strip()

    if not value:
        return None

    if not value.startswith("/vendor"):
        return None

    if value.startswith("//"):
        return None

    return value


def _send_reset_link(vendor):
    if not vendor.email:
        return False, "No email address is stored for this translator."

    token = generate_vendor_reset_token(vendor)

    reset_url = url_for(
        "vendor_portal.reset_password",
        token=token,
        _external=True,
    )

    ok, error, _ = send_vendor_password_reset_email(
        vendor,
        reset_url,
    )

    return ok, error


def _vendor_assignment_query(vendor):
    return (
        OperationsJobcardAssignment.query
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id
            == OperationsJobcardAssignment.jobcard_service_id,
        )
        .filter(
            OperationsJobcardAssignment.assignment_type == "PRODUCTION",
            OperationsJobcardAssignment.assigned_to_type == "VENDOR",
            OperationsJobcardAssignment.vendor_id == vendor.id,
        )
    )


def _get_vendor_assignment_or_404(vendor, assignment_id):
    assignment = (
        _vendor_assignment_query(vendor)
        .filter(OperationsJobcardAssignment.id == assignment_id)
        .first_or_404()
    )
    return assignment


def _amount_for_assignment(assignment):
    qty = Decimal(str(assignment.assigned_qty or 0))
    rate = Decimal(str(assignment.rate or 0))

    if assignment.flat_rate:
        return rate

    return qty * rate


def _safe_static_file(relative_path):
    """
    Resolve a DB path that is stored relative to app/static without allowing
    directory traversal.
    """
    relative_path = (relative_path or "").strip().replace("\\", "/")
    if not relative_path:
        return None

    static_root = os.path.abspath(
        os.path.join(current_app.root_path, "static")
    )
    full_path = os.path.abspath(
        os.path.join(static_root, relative_path)
    )

    if full_path != static_root and not full_path.startswith(
        static_root + os.sep
    ):
        abort(403)

    if not os.path.isfile(full_path):
        return None

    return full_path


def _save_vendor_checklist_file(file_obj):
    if not file_obj or not file_obj.filename:
        return None, None

    original_name = secure_filename(file_obj.filename)
    if not original_name:
        raise ValueError("Invalid submission filename.")

    ext = os.path.splitext(original_name)[1].lower()

    if ext and ext not in ALLOWED_VENDOR_UPLOAD_EXTENSIONS:
        raise ValueError(
            "Unsupported checklist attachment type."
        )

    upload_root = os.path.join(
        current_app.root_path,
        "static",
        "uploads",
        "vendor_checklist",
    )
    os.makedirs(upload_root, exist_ok=True)

    stored_name = f"{uuid.uuid4().hex}{ext}"
    absolute_path = os.path.join(upload_root, stored_name)
    file_obj.save(absolute_path)

    return (
        original_name,
        f"uploads/vendor_checklist/{stored_name}",
    )


def _field_values_for_service(service):
    rows = (
        OperationsJobcardFieldValue.query
        .filter_by(jobcard_service_id=service.id)
        .order_by(OperationsJobcardFieldValue.id.asc())
        .all()
    )
    return rows


def _checklist_questions_for_service(service):
    return (
        OperationsChecklistQuestion.query
        .filter(
            OperationsChecklistQuestion.jobcard_service_id == service.id,
            or_(
                OperationsChecklistQuestion.checklist_for == "VENDOR",
                OperationsChecklistQuestion.checklist_for.is_(None),
            ),
        )
        .order_by(
            OperationsChecklistQuestion.sort_order.asc(),
            OperationsChecklistQuestion.id.asc(),
        )
        .all()
    )


def _checklist_response_map(assignment):
    rows = (
        OperationsChecklistResponse.query
        .filter_by(assignment_id=assignment.id)
        .all()
    )
    return {
        row.checklist_question_id: row
        for row in rows
    }


def _save_vendor_checklist(assignment, questions):
    """
    Save the checklist and return validation errors.

    A vendor may mark a job complete only when every required checklist
    question has a valid response. Required checkboxes must be explicitly
    confirmed (Yes). Optional checklist items remain optional.
    """
    response_map = _checklist_response_map(assignment)
    errors = []

    for question in questions:
        input_name = f"checklist_{question.id}"
        existing = response_map.get(question.id)
        file_path = None
        response_value = None

        if question.question_type == "file":
            upload = request.files.get(input_name)

            if upload and upload.filename:
                try:
                    original_name, file_path = _save_vendor_checklist_file(upload)
                except ValueError as exc:
                    errors.append(f"{question.question_text}: {exc}")
                    continue
                response_value = original_name
            elif existing and existing.file_path:
                file_path = existing.file_path
                response_value = existing.response_value

        elif question.question_type == "checkbox":
            response_value = "Yes" if request.form.get(input_name) == "1" else "No"

        else:
            response_value = (request.form.get(input_name) or "").strip()

        if question.is_required:
            if question.question_type == "checkbox" and response_value != "Yes":
                errors.append(f"Please confirm checklist item: {question.question_text}")
                continue
            if question.question_type != "checkbox" and not response_value and not file_path:
                errors.append(f"Required checklist item: {question.question_text}")
                continue

        if not existing:
            existing = OperationsChecklistResponse(
                checklist_question_id=question.id,
                jobcard_service_id=assignment.jobcard_service_id,
                assignment_id=assignment.id,
            )
            db.session.add(existing)

        existing.response_value = response_value
        existing.file_path = file_path or existing.file_path
        existing.submitted_at = _now()

    return errors


def _refresh_operations_status_after_completion(assignment):
    """Reuse the application's current Operations completion aggregation."""
    try:
        from app.operations.routes import (
            _refresh_service_assignment_status,
            _refresh_jobcard_status,
        )
        service = assignment.jobcard_service
        _refresh_service_assignment_status(service)
        _refresh_jobcard_status(service.jobcard)
    except Exception:
        # The assignment itself is still safely Completed. Do not block the
        # vendor because a future Operations helper was renamed.
        pass


def _vendor_profile(vendor, create=False):
    profile = getattr(vendor, "billing_profile", None)
    if profile is None and create:
        profile = VendorBillingProfile(vendor_id=vendor.id)
        db.session.add(profile)
    return profile


def _profile_is_complete(vendor):
    profile = _vendor_profile(vendor, create=False)
    return bool(profile and profile.is_complete)


def _snapshot_billing_details(invoice, profile, branch):
    """Freeze vendor and Crystal Hues bill-to details on the invoice."""
    company = branch.company if branch else None
    invoice.bill_to_company_name = (company.name if company else None) or "Crystal Hues"
    invoice.bill_to_branch_name = branch.branch_name if branch else None
    invoice.bill_to_address = branch.branch_address if branch else None
    invoice.bill_to_gst_no = branch.gst_no if branch else None

    invoice.vendor_beneficiary_name = profile.beneficiary_name
    invoice.vendor_billing_address = profile.billing_address
    invoice.vendor_bank_name = profile.bank_name
    invoice.vendor_bank_address = profile.bank_address
    invoice.vendor_bank_account_number = profile.bank_account_number
    invoice.vendor_ifsc_code = profile.ifsc_code
    invoice.vendor_swift_code = profile.swift_code
    invoice.vendor_iban = profile.iban
    invoice.vendor_paypal_id = profile.paypal_id
    invoice.vendor_pan_number = profile.pan_number
    invoice.vendor_gst_registered = profile.gst_registered
    invoice.vendor_gstin = profile.gstin


def _backfill_existing_invoice_snapshots(vendor, profile):
    """Populate missing snapshots for invoices raised before profile capture existed.

    Vendor data is frozen using the first confirmed portal profile. Bill-to data
    is frozen only when the legacy invoice resolves to exactly one company
    branch; mixed-branch legacy invoices are left linked dynamically.
    """
    invoices = VendorInvoice.query.filter_by(vendor_id=vendor.id).all()
    for invoice in invoices:
        if not invoice.vendor_beneficiary_name:
            invoice.vendor_beneficiary_name = profile.beneficiary_name
        if not invoice.vendor_billing_address:
            invoice.vendor_billing_address = profile.billing_address
        if not invoice.vendor_bank_name:
            invoice.vendor_bank_name = profile.bank_name
        if not invoice.vendor_bank_address:
            invoice.vendor_bank_address = profile.bank_address
        if not invoice.vendor_bank_account_number:
            invoice.vendor_bank_account_number = profile.bank_account_number
        if not invoice.vendor_ifsc_code:
            invoice.vendor_ifsc_code = profile.ifsc_code
        if not invoice.vendor_swift_code:
            invoice.vendor_swift_code = profile.swift_code
        if not invoice.vendor_iban:
            invoice.vendor_iban = profile.iban
        if not invoice.vendor_paypal_id:
            invoice.vendor_paypal_id = profile.paypal_id
        if not invoice.vendor_pan_number:
            invoice.vendor_pan_number = profile.pan_number
        if invoice.vendor_gst_registered is None:
            invoice.vendor_gst_registered = profile.gst_registered
        if not invoice.vendor_gstin:
            invoice.vendor_gstin = profile.gstin

        if not invoice.bill_to_branch_name:
            branches = []
            seen = set()
            for item in invoice.items or []:
                customer_invoice = item.customer_invoice
                branch = customer_invoice.company_branch if customer_invoice else None
                if branch and branch.id not in seen:
                    seen.add(branch.id)
                    branches.append(branch)
            if len(branches) == 1:
                branch = branches[0]
                company = branch.company if branch else None
                invoice.bill_to_company_name = (company.name if company else None) or "Crystal Hues"
                invoice.bill_to_branch_name = branch.branch_name
                invoice.bill_to_address = branch.branch_address
                invoice.bill_to_gst_no = branch.gst_no


def _privacy_json_value(value):
    if value is None:
        return None
    if isinstance(value, (datetime, date)):
        return value.isoformat()
    if isinstance(value, Decimal):
        return str(value)
    return value


def _safe_remove_vendor_file(relative_path, vendor_id):
    """Delete a vendor-uploaded file without allowing path traversal."""
    if not relative_path:
        return False
    rel = str(relative_path).replace("\\", "/").lstrip("/")
    allowed_prefix = "uploads/vendor_onboarding/{}/".format(vendor_id)
    if not rel.startswith(allowed_prefix):
        return False
    static_root = os.path.realpath(os.path.join(current_app.root_path, "static"))
    target = os.path.realpath(os.path.join(static_root, rel))
    if not target.startswith(static_root + os.sep):
        return False
    try:
        if os.path.isfile(target):
            os.remove(target)
            return True
    except OSError:
        current_app.logger.exception("Unable to remove vendor privacy file vendor_id=%s path=%s", vendor_id, rel)
    return False


def _vendor_privacy_export(vendor):
    onboarding = getattr(vendor, "onboarding_profile", None)
    billing = getattr(vendor, "billing_profile", None)
    assignments = OperationsJobcardAssignment.query.filter_by(vendor_id=vendor.id).order_by(OperationsJobcardAssignment.assigned_at.asc()).all()
    invoices = VendorInvoice.query.filter_by(vendor_id=vendor.id).order_by(VendorInvoice.invoice_date.asc(), VendorInvoice.id.asc()).all()
    capabilities = VendorServiceCapability.query.filter_by(vendor_id=vendor.id).order_by(VendorServiceCapability.id.asc()).all()

    profile = {
        "vendor_id": vendor.id,
        "translator_id": vendor.external_translator_id,
        "name": vendor.name,
        "email": vendor.email,
        "phone": vendor.phone,
        "currency": vendor.currency,
        "status": vendor.translator_status,
        "email_verified_at": _privacy_json_value(vendor.email_verified_at),
        "portal_created_at": _privacy_json_value(vendor.portal_created_at),
        "last_login_at": _privacy_json_value(vendor.last_login_at),
    }
    if onboarding:
        profile["onboarding"] = {
            "primary_phone": onboarding.primary_phone,
            "secondary_phone": onboarding.secondary_phone,
            "country": onboarding.country,
            "address": onboarding.address,
            "date_of_birth": _privacy_json_value(onboarding.date_of_birth),
            "gender": onboarding.gender,
            "years_of_experience": _privacy_json_value(onboarding.years_of_experience),
            "native_language": onboarding.native_language.name if onboarding.native_language else onboarding.native_language_other,
            "voice_modulation_type": onboarding.voice_modulation_type,
            "domains": [d.name for d in onboarding.domains],
            "id_type": onboarding.id_type,
            "id_number": onboarding.id_number,
            "verification_status": onboarding.verification_status,
            "submitted_at": _privacy_json_value(onboarding.submitted_at),
            "verified_at": _privacy_json_value(onboarding.verified_at),
            "uploaded_files": {
                "bank_verification_document": onboarding.bank_verification_document,
                "identity_document": onboarding.id_document,
                "resume": onboarding.resume_document,
            },
        }
    if billing:
        profile["current_billing_profile"] = {
            "beneficiary_name": billing.beneficiary_name,
            "billing_address": billing.billing_address,
            "bank_name": billing.bank_name,
            "bank_address": billing.bank_address,
            "bank_account_number": billing.bank_account_number,
            "ifsc_code": billing.ifsc_code,
            "swift_code": billing.swift_code,
            "iban": billing.iban,
            "paypal_id": billing.paypal_id,
            "pan_number": billing.pan_number,
            "gst_registered": billing.gst_registered,
            "gstin": billing.gstin,
            "updated_at": _privacy_json_value(billing.updated_at),
        }

    jobs = []
    for a in assignments:
        svc = a.jobcard_service
        jc = svc.jobcard if svc else None
        jobs.append({
            "assignment_id": a.id,
            "jobcard": jc.jobcard_code if jc else None,
            "service": svc.service_name if svc else None,
            "assignment_type": a.assignment_type,
            "quantity": _privacy_json_value(a.assigned_qty),
            "rate": _privacy_json_value(a.rate),
            "flat_rate": bool(a.flat_rate),
            "deadline": _privacy_json_value(a.deadline),
            "assigned_at": _privacy_json_value(a.assigned_at),
            "completed_at": _privacy_json_value(a.completed_at),
            "status": a.status,
        })

    service_data = []
    for c in capabilities:
        service_data.append({
            "service": c.service.name if c.service else None,
            "status": c.status,
            "final_level": c.final_level,
            "approved_at": _privacy_json_value(c.approved_at),
            "rates": [{
                "language_pair": r.language_pair.display_name if r.language_pair else None,
                "rate": _privacy_json_value(r.rate),
                "currency": r.currency,
                "unit": r.unit,
                "vendor_submitted_rate": _privacy_json_value(r.vendor_submitted_rate),
                "final_rate": _privacy_json_value(r.final_rate),
                "negotiation_status": r.negotiation_status,
            } for r in c.rates.all()],
        })

    invoice_data = []
    for inv in invoices:
        invoice_data.append({
            "invoice_id": inv.id,
            "vendor_invoice_no": inv.vendor_invoice_no,
            "invoice_date": _privacy_json_value(inv.invoice_date),
            "due_date": _privacy_json_value(inv.due_date),
            "currency": inv.currency,
            "taxable_amount": _privacy_json_value(inv.taxable_amount),
            "gst_amount": _privacy_json_value(inv.gst_amount),
            "total_amount": _privacy_json_value(inv.total_amount),
            "tds_amount": _privacy_json_value(inv.tds_amount),
            "net_payable_amount": _privacy_json_value(inv.net_payable_amount),
            "payment_status": inv.payment_status,
            "billing_snapshot": {
                "beneficiary_name": inv.vendor_beneficiary_name,
                "billing_address": inv.vendor_billing_address,
                "bank_name": inv.vendor_bank_name,
                "bank_address": inv.vendor_bank_address,
                "bank_account_number": inv.vendor_bank_account_number,
                "ifsc_code": inv.vendor_ifsc_code,
                "swift_code": inv.vendor_swift_code,
                "iban": inv.vendor_iban,
                "paypal_id": inv.vendor_paypal_id,
                "pan_number": inv.vendor_pan_number,
                "gstin": inv.vendor_gstin,
            },
            "payments": [{
                "status": p.status,
                "payment_mode": p.payment_mode,
                "payment_date": _privacy_json_value(p.payment_date),
                "amount": _privacy_json_value(p.amount),
                "currency": p.currency,
                "reference": p.reference,
                "created_at": _privacy_json_value(p.created_at),
            } for p in (inv.payment_transactions or [])],
            "items": [{
                "jobcard": item.jobcard_code,
                "service": item.service_name,
                "quantity": _privacy_json_value(item.quantity),
                "rate": _privacy_json_value(item.rate),
                "flat_rate": bool(item.flat_rate),
                "amount": _privacy_json_value(item.amount),
            } for item in (inv.items or [])],
        })

    return {
        "exported_at": _now().isoformat() + "Z",
        "privacy_notice_version": PRIVACY_NOTICE_VERSION,
        "profile": profile,
        "services_and_rates": service_data,
        "job_history": jobs,
        "billing_and_payment_history": invoice_data,
        "nda_signatures": [{
            "document": sig.nda_document.title if sig.nda_document else None,
            "version": sig.nda_document.version if sig.nda_document else None,
            "signer_name": sig.signer_name,
            "signed_at": _privacy_json_value(sig.signed_at),
            "expires_at": _privacy_json_value(sig.expires_at),
        } for sig in vendor.nda_signatures.all()],
    }


def _erase_vendor_profile(vendor):
    """Irreversibly erase direct vendor PII while retaining job/accounting evidence."""
    first_name = ((vendor.name or "Vendor").strip().split() or ["Vendor"])[0][:150]
    removed_files = 0
    onboarding = getattr(vendor, "onboarding_profile", None)
    if onboarding:
        for path in (onboarding.bank_verification_document, onboarding.id_document, onboarding.resume_document):
            removed_files += 1 if _safe_remove_vendor_file(path, vendor.id) else 0

    capabilities = VendorServiceCapability.query.filter_by(vendor_id=vendor.id).all()
    for capability in capabilities:
        for sample in capability.work_samples.all():
            removed_files += 1 if _safe_remove_vendor_file(sample.file_path, vendor.id) else 0

    # Reviews performed by this vendor against somebody else's qualification are
    # de-linked so the reviewer can no longer be identified.
    VendorServiceTest.query.filter_by(peer_reviewer_vendor_id=vendor.id).update({
        VendorServiceTest.peer_reviewer_vendor_id: None,
        VendorServiceTest.peer_feedback: None,
    }, synchronize_session=False)

    # Historical job links remain, but any denormalised full-name snapshot is minimised.
    OperationsJobcardService.query.filter_by(vendor_id=vendor.id).update({
        OperationsJobcardService.vendor_name: first_name,
    }, synchronize_session=False)
    XbenchReport.query.filter_by(translator_vendor_id=vendor.id).update({
        XbenchReport.translator_name_snapshot: first_name,
    }, synchronize_session=False)

    # NDA execution is retained only as a minimal legal record; device/network data
    # and the full signer name are erased.
    for signature in vendor.nda_signatures.all():
        signature.signer_name = first_name
        signature.ip_address = None
        signature.user_agent = None

    # Remove portal/onboarding data that is no longer necessary after closure.
    VendorEmailOTP.query.filter_by(vendor_id=vendor.id).delete(synchronize_session=False)
    VendorServiceRequest.query.filter_by(vendor_id=vendor.id).delete(synchronize_session=False)
    for capability in capabilities:
        db.session.delete(capability)
    if onboarding:
        db.session.delete(onboarding)
    billing = getattr(vendor, "billing_profile", None)
    if billing:
        db.session.delete(billing)

    # Status remarks can contain free-text personal information. Keep status history
    # itself for accountability but remove free-text remarks.
    for status_event in vendor.status_history.all():
        status_event.remark = None

    reference = "ERASE-{}-{}".format(vendor.id, uuid.uuid4().hex[:12].upper())
    original_translator_id = vendor.external_translator_id
    original_id_hash = hashlib.sha256((original_translator_id or "").strip().lower().encode("utf-8")).hexdigest()
    if original_translator_id and not VendorPrivacyTombstone.query.filter_by(external_identifier_hash=original_id_hash).first():
        db.session.add(VendorPrivacyTombstone(
            external_identifier_hash=original_id_hash,
            erasure_reference=reference,
        ))
    vendor.name = first_name
    vendor.email = None
    vendor.phone = None
    vendor.currency = None
    vendor.tally_ledger_name = None
    vendor.profile_summary = None
    vendor.portal_password_hash = None
    vendor.portal_active = False
    vendor.portal_must_change_password = False
    vendor.last_login_at = None
    vendor.password_changed_at = None
    vendor.failed_login_count = 0
    vendor.locked_until = None
    vendor.email_verified_at = None
    vendor.is_active = False
    vendor.translator_status = "INACTIVE"
    vendor.onboarding_status = "EXEMPT"
    vendor.external_translator_id = "GDPR-{}-{}".format(vendor.id, uuid.uuid4().hex[:10].upper())
    vendor.privacy_erased_at = _now()
    vendor.privacy_erasure_reference = reference
    vendor.portal_updated_at = _now()

    event = VendorPrivacyEvent(
        vendor_id=vendor.id,
        event_type="ACCOUNT_ERASED",
        policy_version=PRIVACY_NOTICE_VERSION,
        reference=reference,
        metadata_json=json.dumps({
            "files_removed": removed_files,
            "job_links_retained": OperationsJobcardAssignment.query.filter_by(vendor_id=vendor.id).count(),
            "financial_records_retained": VendorInvoice.query.filter_by(vendor_id=vendor.id).count(),
            "previous_translator_id_hash": original_id_hash,
        }, sort_keys=True),
    )
    db.session.add(event)
    return reference


@vendor_portal_bp.route("/privacy-notice")
def privacy_notice():
    return render_template(
        "vendor_portal/privacy_notice.html",
        policy_version=PRIVACY_NOTICE_VERSION,
        controller_name=current_app.config.get("PRIVACY_CONTROLLER_NAME", "Crystal Hues Limited"),
        privacy_contact=current_app.config.get("PRIVACY_CONTACT_EMAIL") or "Privacy contact not configured",
        dpo_contact=current_app.config.get("PRIVACY_DPO_EMAIL"),
    )


@vendor_portal_bp.route("/privacy")
@vendor_login_required
def privacy_center():
    vendor = get_current_vendor()
    onboarding = getattr(vendor, "onboarding_profile", None)
    billing = getattr(vendor, "billing_profile", None)
    counts = {
        "jobs": OperationsJobcardAssignment.query.filter_by(vendor_id=vendor.id).count(),
        "invoices": VendorInvoice.query.filter_by(vendor_id=vendor.id).count(),
        "services": VendorServiceCapability.query.filter_by(vendor_id=vendor.id).count(),
        "nda_signatures": vendor.nda_signatures.count(),
    }
    return render_template(
        "vendor_portal/privacy_center.html",
        vendor=vendor,
        onboarding=onboarding,
        billing=billing,
        counts=counts,
        policy_version=PRIVACY_NOTICE_VERSION,
        controller_name=current_app.config.get("PRIVACY_CONTROLLER_NAME", "Crystal Hues Limited"),
        privacy_contact=current_app.config.get("PRIVACY_CONTACT_EMAIL") or "Privacy contact not configured",
    )


@vendor_portal_bp.route("/privacy/export", methods=["POST"])
@vendor_login_required
def privacy_export():
    vendor = get_current_vendor()
    payload = _vendor_privacy_export(vendor)
    db.session.add(VendorPrivacyEvent(vendor_id=vendor.id, event_type="DATA_EXPORTED", policy_version=PRIVACY_NOTICE_VERSION))
    db.session.commit()
    raw = json.dumps(payload, indent=2, ensure_ascii=False, default=_privacy_json_value).encode("utf-8")
    return send_file(
        BytesIO(raw),
        mimetype="application/json",
        as_attachment=True,
        download_name="Crystal_Nexus_My_Data_{}.json".format(vendor.id),
    )


@vendor_portal_bp.route("/privacy/delete-account", methods=["POST"])
@vendor_login_required
def privacy_delete_account():
    vendor = get_current_vendor()
    password = request.form.get("password") or ""
    confirmation = (request.form.get("confirmation") or "").strip().upper()
    acknowledge_retention = request.form.get("acknowledge_retention") == "1"
    if confirmation != "DELETE":
        flash("Type DELETE exactly to confirm account deletion.", "danger")
        return redirect(url_for("vendor_portal.privacy_center"))
    if not acknowledge_retention:
        flash("Please acknowledge the records that must be retained before continuing.", "danger")
        return redirect(url_for("vendor_portal.privacy_center"))
    if not vendor.check_portal_password(password):
        flash("Your password could not be verified. No data was deleted.", "danger")
        return redirect(url_for("vendor_portal.privacy_center"))

    reference = _erase_vendor_profile(vendor)
    db.session.commit()
    session.pop(VENDOR_SESSION_KEY, None)
    session.clear()
    flash("Your Vendor Portal account has been closed and personal profile data erased. Reference: {}".format(reference), "success")
    return redirect(url_for("vendor_portal.login"))


@vendor_portal_bp.route("/privacy/acknowledge", methods=["POST"])
@vendor_login_required
def privacy_acknowledge():
    vendor = get_current_vendor()
    exists = VendorPrivacyEvent.query.filter_by(
        vendor_id=vendor.id,
        event_type="NOTICE_ACKNOWLEDGED",
        policy_version=PRIVACY_NOTICE_VERSION,
    ).first()
    if not exists:
        db.session.add(VendorPrivacyEvent(
            vendor_id=vendor.id,
            event_type="NOTICE_ACKNOWLEDGED",
            policy_version=PRIVACY_NOTICE_VERSION,
        ))
        db.session.commit()
    flash("Privacy Notice acknowledgement recorded.", "success")
    return redirect(request.referrer or url_for("vendor_portal.privacy_center"))


@vendor_portal_bp.app_context_processor
def inject_vendor_portal_context():
    vendor = get_current_vendor()
    privacy_notice_acknowledged = False
    if vendor:
        privacy_notice_acknowledged = bool(VendorPrivacyEvent.query.filter_by(
            vendor_id=vendor.id,
            event_type="NOTICE_ACKNOWLEDGED",
            policy_version=PRIVACY_NOTICE_VERSION,
        ).first())
    return {
        "portal_vendor": vendor,
        "portal_profile_complete": _profile_is_complete(vendor) if vendor else False,
        "portal_privacy_notice_acknowledged": privacy_notice_acknowledged,
        "portal_privacy_notice_version": PRIVACY_NOTICE_VERSION,
    }


@vendor_portal_bp.route("/login", methods=["GET", "POST"])
def login():
    current_vendor = get_current_vendor()

    if current_vendor is not None:
        return redirect(
            url_for("vendor_portal.dashboard")
        )

    if request.method == "POST":
        trans_id = (
            request.form.get("trans_id") or ""
        ).strip()
        password = request.form.get("password") or ""

        if not trans_id or not password:
            flash(
                "Please enter your TransId and password.",
                "danger",
            )
            return render_template(
                "vendor_portal/login.html",
                trans_id=trans_id,
            )

        vendor = (
            VendorMaster.query
            .filter(
                or_(
                    func.lower(VendorMaster.external_translator_id) == trans_id.lower(),
                    func.lower(VendorMaster.email) == trans_id.lower(),
                )
            )
            .first()
        )

        invalid_message = "Invalid TransId or password."

        if vendor is None:
            flash(invalid_message, "danger")
            return render_template(
                "vendor_portal/login.html",
                trans_id=trans_id,
            )

        now = _now()

        if (
            vendor.locked_until
            and vendor.locked_until > now
        ):
            flash(
                "This account is temporarily locked after repeated failed "
                "login attempts. Please try again later or use Forgot Password.",
                "danger",
            )
            return render_template(
                "vendor_portal/login.html",
                trans_id=trans_id,
            )

        if not vendor.can_login_to_portal():
            flash(
                "Vendor Portal access has not been activated for this TransId. "
                "Please contact your Crystal Hues project manager.",
                "warning",
            )
            return render_template(
                "vendor_portal/login.html",
                trans_id=trans_id,
            )

        if not vendor.check_portal_password(password):
            vendor.failed_login_count = int(
                vendor.failed_login_count or 0
            ) + 1

            if vendor.failed_login_count >= MAX_FAILED_LOGINS:
                vendor.locked_until = now + timedelta(
                    minutes=LOCK_MINUTES
                )
                vendor.failed_login_count = 0

            db.session.commit()
            flash(invalid_message, "danger")

            return render_template(
                "vendor_portal/login.html",
                trans_id=trans_id,
            )

        vendor.reset_portal_login_failures()
        vendor.last_login_at = now
        vendor.portal_updated_at = now
        db.session.commit()

        # Internal Crystal Nexus login and Vendor Portal may coexist.
        session[VENDOR_SESSION_KEY] = vendor.id
        session.permanent = True

        if vendor.portal_must_change_password:
            flash(
                "Please create a new password before continuing.",
                "info",
            )
            return redirect(
                url_for("vendor_portal.change_password")
            )

        if not _profile_is_complete(vendor):
            has_existing_invoices = VendorInvoice.query.filter_by(vendor_id=vendor.id).first() is not None
            if has_existing_invoices:
                flash(
                    "Please update your billing address and payment profile now. "
                    "These details are required for vendor invoices and future payments.",
                    "warning",
                )
            else:
                flash(
                    "Complete your billing and payment profile before raising your first invoice.",
                    "warning",
                )
            return redirect(url_for("vendor_portal.my_profile"))

        next_url = _safe_next_url(
            request.args.get("next")
        )

        return redirect(
            next_url
            or url_for("vendor_portal.dashboard")
        )

    return render_template(
        "vendor_portal/login.html",
        trans_id="",
    )


@vendor_portal_bp.route("/logout", methods=["POST"])
def logout():
    session.pop(VENDOR_SESSION_KEY, None)
    flash("You have been signed out.", "success")
    return redirect(
        url_for("vendor_portal.login")
    )


@vendor_portal_bp.route(
    "/forgot-password",
    methods=["GET", "POST"],
)
def forgot_password():
    if request.method == "POST":
        trans_id = (
            request.form.get("trans_id") or ""
        ).strip()

        if trans_id:
            vendor = (
                VendorMaster.query
                .filter(
                    func.lower(
                        VendorMaster.external_translator_id
                    ) == trans_id.lower()
                )
                .first()
            )

            if (
                vendor
                and vendor.portal_active
                and vendor.is_active
                and vendor.email
            ):
                _send_reset_link(vendor)

        # Never reveal whether a TransId exists.
        flash(
            "If the TransId is active and has a registered email address, "
            "a password reset link has been sent.",
            "success",
        )
        return redirect(
            url_for("vendor_portal.login")
        )

    return render_template(
        "vendor_portal/forgot_password.html"
    )


@vendor_portal_bp.route(
    "/reset-password/<token>",
    methods=["GET", "POST"],
)
def reset_password(token):
    vendor = verify_vendor_reset_token(token)

    if vendor is None:
        flash(
            "This password reset link is invalid or has expired. "
            "Please request a new link.",
            "danger",
        )
        return redirect(
            url_for("vendor_portal.forgot_password")
        )

    if request.method == "POST":
        new_password = (
            request.form.get("new_password") or ""
        )
        confirm_password = (
            request.form.get("confirm_password") or ""
        )

        if len(new_password) < 8:
            flash(
                "Password must contain at least 8 characters.",
                "danger",
            )
            return render_template(
                "vendor_portal/reset_password.html",
                token=token,
                vendor=vendor,
            )

        if new_password != confirm_password:
            flash(
                "Password and confirmation do not match.",
                "danger",
            )
            return render_template(
                "vendor_portal/reset_password.html",
                token=token,
                vendor=vendor,
            )

        vendor.set_portal_password(
            new_password,
            must_change=False,
        )
        vendor.reset_portal_login_failures()
        vendor.portal_active = True

        db.session.commit()

        session.pop(VENDOR_SESSION_KEY, None)

        flash(
            "Your password has been reset successfully. "
            "You can now sign in.",
            "success",
        )

        return redirect(
            url_for("vendor_portal.login")
        )

    return render_template(
        "vendor_portal/reset_password.html",
        token=token,
        vendor=vendor,
    )


@vendor_portal_bp.route(
    "/change-password",
    methods=["GET", "POST"],
)
@vendor_login_required
def change_password():
    vendor = get_current_vendor()

    if request.method == "POST":
        current_password = (
            request.form.get("current_password") or ""
        )
        new_password = (
            request.form.get("new_password") or ""
        )
        confirm_password = (
            request.form.get("confirm_password") or ""
        )

        if not vendor.check_portal_password(
            current_password
        ):
            flash(
                "Current password is incorrect.",
                "danger",
            )
            return render_template(
                "vendor_portal/change_password.html"
            )

        if len(new_password) < 8:
            flash(
                "New password must contain at least 8 characters.",
                "danger",
            )
            return render_template(
                "vendor_portal/change_password.html"
            )

        if new_password != confirm_password:
            flash(
                "New password and confirmation do not match.",
                "danger",
            )
            return render_template(
                "vendor_portal/change_password.html"
            )

        if current_password == new_password:
            flash(
                "New password must be different from the current password.",
                "danger",
            )
            return render_template(
                "vendor_portal/change_password.html"
            )

        vendor.set_portal_password(
            new_password,
            must_change=False,
        )
        vendor.reset_portal_login_failures()

        db.session.commit()

        flash(
            "Password updated successfully.",
            "success",
        )

        if not _profile_is_complete(vendor):
            flash(
                "Password updated. Please complete your billing and payment profile before raising invoices.",
                "warning",
            )
            return redirect(url_for("vendor_portal.my_profile"))

        return redirect(
            url_for("vendor_portal.dashboard")
        )

    return render_template(
        "vendor_portal/change_password.html"
    )


def _my_profile_context(vendor, billing_profile, onboarding_profile):
    return dict(
        vendor=vendor,
        profile=billing_profile,
        onboarding_profile=onboarding_profile,
        countries=CountryMaster.query.filter_by(is_active=True).order_by(CountryMaster.sort_order.asc(), CountryMaster.name.asc()).all(),
        currencies=Currency.query.filter_by(is_active=True).order_by(Currency.sort_order.asc(), Currency.code.asc()).all(),
        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(),
        language_pairs=LanguagePairMaster.query.filter_by(is_active=True).order_by(LanguagePairMaster.id.asc()).all(),
        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"),
        capabilities=VendorServiceCapability.query.filter_by(vendor_id=vendor.id).order_by(VendorServiceCapability.id.desc()).all(),
        units=("Per Word", "Per Hour", "Per Page", "Per Minute", "Flat Rate"),
        current_nda=VendorNDADocument.current(_now()),
        nda_signature=(VendorNDASignature.query.filter_by(vendor_id=vendor.id, nda_document_id=VendorNDADocument.current(_now()).id).filter(VendorNDASignature.expires_at >= _now()).first() if VendorNDADocument.current(_now()) else None),
    )


def _save_profile_verification_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 {".pdf", ".jpg", ".jpeg", ".png", ".doc", ".docx"}:
        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"), uuid.uuid4().hex[:8], ext)
    file_obj.save(os.path.join(root, stored))
    return "uploads/vendor_onboarding/{}/{}".format(vendor_id, stored)


@vendor_portal_bp.route("/my-profile", methods=["GET", "POST"])
@vendor_login_required
def my_profile():
    vendor = get_current_vendor()
    billing = _vendor_profile(vendor, create=True)
    onboarding = getattr(vendor, "onboarding_profile", None)
    if onboarding is None:
        onboarding = VendorOnboardingProfile(vendor_id=vendor.id)
        db.session.add(onboarding)
        db.session.flush()

    if request.method == "POST":
        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
        onboarding.primary_phone = (request.form.get("primary_phone") or "").strip() or None
        onboarding.secondary_phone = (request.form.get("secondary_phone") or "").strip() or None

        # Extended profile fields. These are optional so existing vendors are not
        # blocked when the new profile fields are deployed.
        dob_raw = (request.form.get("date_of_birth") or "").strip()
        try:
            onboarding.date_of_birth = datetime.strptime(dob_raw, "%Y-%m-%d").date() if dob_raw else None
        except ValueError:
            onboarding.date_of_birth = None

        gender = (request.form.get("gender") or "").strip()
        allowed_genders = {"Male", "Female", "Non-binary", "Prefer not to say", "Other"}
        onboarding.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
            onboarding.years_of_experience = experience if experience is None or experience >= 0 else None
        except Exception:
            onboarding.years_of_experience = None

        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":
            onboarding.native_language_id = None
            onboarding.native_language_other = native_language_other or None
        else:
            native_language = None
            try:
                native_language_id = int(native_language_value) if native_language_value else None
            except (TypeError, ValueError):
                native_language_id = None
            if native_language_id:
                native_language = LanguageMaster.query.filter_by(id=native_language_id, is_active=True).first()
            onboarding.native_language_id = native_language.id if native_language else None
            onboarding.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"}
        onboarding.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 []
        onboarding.domain_links[:] = [VendorOnboardingDomain(industry_id=industry.id) for industry in valid_industries]

        country_name = (request.form.get("country") or "").strip()
        currency_code = (request.form.get("vendor_currency") or "").strip().upper()
        country = CountryMaster.query.filter(CountryMaster.is_active.is_(True), func.lower(CountryMaster.name) == country_name.lower()).first() if country_name else None
        currency = Currency.query.filter(Currency.is_active.is_(True), func.upper(Currency.code) == currency_code).first() if currency_code else None

        onboarding.address = (request.form.get("billing_address") or "").strip() or None
        onboarding.bank_name = (request.form.get("bank_name") or "").strip() or None
        onboarding.account_holder_name = (request.form.get("beneficiary_name") or "").strip() or None
        onboarding.bank_account_number = (request.form.get("bank_account_number") or "").strip() or None
        onboarding.ifsc_code = (request.form.get("ifsc_code") or "").strip().upper() or None
        onboarding.swift_code = (request.form.get("swift_code") or "").strip().upper() or None
        onboarding.iban = (request.form.get("iban") or "").strip().upper() or None
        onboarding.paypal_id = (request.form.get("paypal_id") or "").strip() or None
        onboarding.id_type = (request.form.get("id_type") or "").strip() or None
        onboarding.id_number = (request.form.get("id_number") or "").strip() or None

        # Billing profile is the pending working copy. It is marked unconfirmed
        # until the Vendor Coordinator approves the profile change.
        billing.beneficiary_name = onboarding.account_holder_name
        billing.billing_address = onboarding.address
        billing.bank_name = onboarding.bank_name
        billing.bank_address = (request.form.get("bank_address") or "").strip() or None
        billing.bank_account_number = onboarding.bank_account_number
        billing.ifsc_code = onboarding.ifsc_code
        billing.swift_code = onboarding.swift_code
        billing.iban = onboarding.iban
        billing.paypal_id = onboarding.paypal_id
        billing.pan_number = (request.form.get("pan_number") or "").strip().upper() or None
        gst_choice = (request.form.get("gst_registered") or "").strip().lower()
        billing.gst_registered = True if gst_choice == "yes" else (False if gst_choice == "no" else None)
        billing.gstin = (request.form.get("gstin") or "").strip().upper() or None

        try:
            bank_doc = _save_profile_verification_file(request.files.get("bank_document"), vendor.id, "bank")
            id_doc = _save_profile_verification_file(request.files.get("id_document"), vendor.id, "identity")
            resume_doc = _save_profile_verification_file(request.files.get("resume_document"), vendor.id, "resume")
        except ValueError as exc:
            flash(str(exc), "danger")
            return render_template("vendor_portal/my_profile.html", **_my_profile_context(vendor, billing, onboarding))
        if bank_doc:
            onboarding.bank_verification_document = bank_doc
        if id_doc:
            onboarding.id_document = id_doc
        if resume_doc:
            onboarding.resume_document = resume_doc

        errors = []
        if dob_raw and onboarding.date_of_birth is None:
            errors.append("Enter a valid Date of Birth.")
        if onboarding.date_of_birth and onboarding.date_of_birth > date.today():
            errors.append("Date of Birth cannot be in the future.")
        if exp_raw and onboarding.years_of_experience is None:
            errors.append("Years of experience must be a valid non-negative number.")
        if native_language_value == "OTHER" and not native_language_other:
            errors.append("Please specify the native language when Others is selected.")
        if not country:
            errors.append("Choose a valid country from Country Master.")
        if not currency:
            errors.append("Choose a valid currency from Currency Master.")
        if not vendor.name:
            errors.append("Name is required.")
        if not onboarding.primary_phone:
            errors.append("Primary contact is required.")
        if not onboarding.address:
            errors.append("Billing address is required.")
        if not onboarding.account_holder_name:
            errors.append("Beneficiary / account holder name is required.")
        if not any((onboarding.bank_account_number, onboarding.iban, onboarding.paypal_id)):
            errors.append("Enter at least one payment destination: bank account number, IBAN, or PayPal ID.")
        if not onboarding.id_type or not onboarding.id_number:
            errors.append("ID type and ID number are required.")
        if currency and currency.code.upper() == "INR":
            if not billing.pan_number:
                errors.append("PAN Card Number is required for INR vendors.")
            elif not re.match(r"^[A-Z]{5}[0-9]{4}[A-Z]$", billing.pan_number):
                errors.append("Enter a valid 10-character PAN (example: ABCDE1234F).")
            if billing.gst_registered is None:
                errors.append("Please select whether you are GST registered.")
            if billing.gst_registered and not billing.gstin:
                errors.append("GSTIN is required when GST Registered is Yes.")
        if request.form.get("profile_confirm") != "1":
            errors.append("Please confirm that the profile information is correct before submitting it for approval.")

        if errors:
            billing.profile_confirmed_at = None
            for error in errors:
                flash(error, "danger")
            return render_template("vendor_portal/my_profile.html", **_my_profile_context(vendor, billing, onboarding))

        onboarding.country = country.name
        vendor.currency = currency.code.upper()
        onboarding.verification_status = "PENDING"
        onboarding.verification_remark = None
        onboarding.submitted_at = _now()
        onboarding.verified_at = None
        onboarding.verified_by_id = None
        vendor.onboarding_status = "IN_PROGRESS"
        vendor.onboarding_started_at = vendor.onboarding_started_at or _now()
        billing.profile_confirmed_at = None
        billing.updated_at = _now()
        db.session.commit()
        flash("Profile changes submitted for approval. Assignment eligibility will resume after approval.", "success")
        return redirect(url_for("vendor_portal.my_profile"))

    # Ensure an approved onboarding profile is visible in Billing without asking
    # the vendor to type the same bank details again.
    if onboarding and onboarding.verification_status == "APPROVED":
        changed = False
        mapping = {
            "beneficiary_name": onboarding.account_holder_name or vendor.name,
            "billing_address": onboarding.address,
            "bank_name": onboarding.bank_name,
            "bank_account_number": onboarding.bank_account_number,
            "ifsc_code": onboarding.ifsc_code,
            "swift_code": onboarding.swift_code,
            "iban": onboarding.iban,
            "paypal_id": onboarding.paypal_id,
        }
        for field, value in mapping.items():
            if value and not getattr(billing, field):
                setattr(billing, field, value)
                changed = True
        if changed:
            db.session.commit()

    return render_template("vendor_portal/my_profile.html", **_my_profile_context(vendor, billing, onboarding))


@vendor_portal_bp.route("/")
@vendor_portal_bp.route("/dashboard")
@vendor_login_required
def dashboard():
    vendor = get_current_vendor()
    base_query = _vendor_assignment_query(vendor)

    assigned_count = base_query.filter(OperationsJobcardAssignment.status == "Assigned").count()
    in_progress_count = base_query.filter(OperationsJobcardAssignment.status == "In Progress").count()
    completed_count = base_query.filter(OperationsJobcardAssignment.status == "Completed").count()

    recent_assignments = (
        base_query
        .filter(OperationsJobcardAssignment.status.notin_(["Cancelled", "Replaced"]))
        .order_by(OperationsJobcardAssignment.assigned_at.desc())
        .limit(6)
        .all()
    )

    ready_rows = _ready_to_invoice_rows(vendor)
    ready_to_invoice_count = len(ready_rows)
    ready_to_invoice_value = sum((r["amount"] for r in ready_rows), Decimal("0"))

    vendor_invoices = (
        VendorInvoice.query
        .filter_by(vendor_id=vendor.id)
        .order_by(VendorInvoice.raised_at.desc(), VendorInvoice.id.desc())
        .all()
    )
    raised_invoice_count = len(vendor_invoices)
    total_invoiced = sum((Decimal(str(i.total_amount or 0)) for i in vendor_invoices), Decimal("0"))
    pending_invoices = [i for i in vendor_invoices if i.payment_status != "Paid"]
    pending_payment_count = len(pending_invoices)
    pending_payment_value = sum((Decimal(str(i.total_amount or 0)) for i in pending_invoices), Decimal("0"))
    paid_value = sum((Decimal(str(i.total_amount or 0)) for i in vendor_invoices if i.payment_status == "Paid"), Decimal("0"))
    next_due_date = min((i.due_date for i in pending_invoices if i.due_date), default=None)

    return render_template(
        "vendor_portal/dashboard.html",
        vendor=vendor,
        assigned_count=assigned_count,
        in_progress_count=in_progress_count,
        completed_count=completed_count,
        recent_assignments=recent_assignments,
        ready_to_invoice_count=ready_to_invoice_count,
        ready_to_invoice_value=ready_to_invoice_value,
        raised_invoice_count=raised_invoice_count,
        total_invoiced=total_invoiced,
        pending_payment_count=pending_payment_count,
        pending_payment_value=pending_payment_value,
        paid_value=paid_value,
        next_due_date=next_due_date,
        recent_invoices=vendor_invoices[:5],
    )


@vendor_portal_bp.route("/jobs")
@vendor_login_required
def assigned_jobs():
    vendor = get_current_vendor()

    q = (request.args.get("q") or "").strip()
    status = (request.args.get("status") or "").strip()

    query = (
        _vendor_assignment_query(vendor)
        .filter(
            OperationsJobcardAssignment.status.notin_(
                ["Completed", "Cancelled", "Replaced"]
            )
        )
    )

    if q:
        like = f"%{q}%"
        query = (
            query
            .join(
                OperationsJobcardService.jobcard
            )
            .filter(
                or_(
                    OperationsJobcardService.service_name.ilike(like),
                    OperationsJobcardService.jobcard.has(
                        jobcard_code= q
                    ),
                )
            )
        )

    if status:
        query = query.filter(
            OperationsJobcardAssignment.status == status
        )

    assignments = (
        query
        .order_by(
            OperationsJobcardAssignment.deadline.asc(),
            OperationsJobcardAssignment.assigned_at.desc(),
        )
        .all()
    )

    return render_template(
        "vendor_portal/assigned_jobs.html",
        vendor=vendor,
        assignments=assignments,
        q=q,
        status=status,
        now=_now(),
        amount_for_assignment=_amount_for_assignment,
    )


@vendor_portal_bp.route("/jobs/completed")
@vendor_login_required
def completed_jobs():
    vendor = get_current_vendor()

    q = (request.args.get("q") or "").strip()

    query = (
        _vendor_assignment_query(vendor)
        .filter(
            OperationsJobcardAssignment.status == "Completed"
        )
    )

    if q:
        like = f"%{q}%"
        query = (
            query
            .join(OperationsJobcardService.jobcard)
            .filter(
                or_(
                    OperationsJobcardService.service_name.ilike(like),
                    OperationsJobcardService.jobcard.has(
                        jobcard_code=q
                    ),
                )
            )
        )

    assignments = (
        query
        .order_by(
            OperationsJobcardAssignment.completed_at.desc(),
            OperationsJobcardAssignment.id.desc(),
        )
        .all()
    )

    return render_template(
        "vendor_portal/completed_jobs.html",
        vendor=vendor,
        assignments=assignments,
        q=q,
        amount_for_assignment=_amount_for_assignment,
    )


@vendor_portal_bp.route("/jobs/<int:assignment_id>")
@vendor_login_required
def job_detail(assignment_id):
    vendor = get_current_vendor()
    assignment = _get_vendor_assignment_or_404(
        vendor,
        assignment_id,
    )

    service = assignment.jobcard_service
    jobcard = service.jobcard

    field_values = _field_values_for_service(service)
    questions = _checklist_questions_for_service(service)
    response_map = _checklist_response_map(assignment)

    return render_template(
        "vendor_portal/job_detail.html",
        vendor=vendor,
        assignment=assignment,
        service=service,
        jobcard=jobcard,
        field_values=field_values,
        questions=questions,
        response_map=response_map,
        amount=_amount_for_assignment(assignment),
        now=_now(),
    )


@vendor_portal_bp.route(
    "/jobs/<int:assignment_id>/accept",
    methods=["POST"],
)
@vendor_login_required
def accept_job(assignment_id):
    vendor = get_current_vendor()
    assignment = _get_vendor_assignment_or_404(vendor, assignment_id)

    if assignment.status != "Assigned":
        flash("Only newly assigned jobs can be accepted.", "warning")
        return redirect(url_for("vendor_portal.job_detail", assignment_id=assignment.id))

    assignment.status = "In Progress"
    db.session.commit()

    flash("Job accepted successfully. You can mark it complete after finishing the checklist.", "success")
    return redirect(url_for("vendor_portal.job_detail", assignment_id=assignment.id))


@vendor_portal_bp.route(
    "/jobs/<int:assignment_id>/complete",
    methods=["POST"],
)
@vendor_login_required
def complete_job(assignment_id):
    vendor = get_current_vendor()
    assignment = _get_vendor_assignment_or_404(vendor, assignment_id)

    if assignment.status == "Completed":
        flash("This assignment is already completed.", "info")
        return redirect(url_for("vendor_portal.job_detail", assignment_id=assignment.id))

    if assignment.status in ["Cancelled", "Replaced"]:
        flash("This assignment cannot be completed in its current status.", "warning")
        return redirect(url_for("vendor_portal.job_detail", assignment_id=assignment.id))

    if assignment.status != "In Progress":
        flash("Please accept the job before marking it complete.", "warning")
        return redirect(url_for("vendor_portal.job_detail", assignment_id=assignment.id))

    questions = _checklist_questions_for_service(assignment.jobcard_service)
    checklist_errors = _save_vendor_checklist(assignment, questions)

    if checklist_errors:
        db.session.rollback()
        for error in checklist_errors[:8]:
            flash(error, "danger")
        flash("Complete the required checklist items before marking the job complete.", "danger")
        return redirect(url_for("vendor_portal.job_detail", assignment_id=assignment.id))

    now = _now()
    assignment.status = "Completed"
    assignment.completed_at = now
    assignment.completion_remark = (request.form.get("completion_remark") or "").strip() or None

    if questions:
        assignment.checklist_status = "Completed"
        assignment.checklist_submitted_at = now

    # Clear obsolete portal-review state if this record had been used during UAT.
    assignment.vendor_review_status = "NOT_SUBMITTED"
    assignment.vendor_review_remark = None
    assignment.vendor_reviewed_at = None
    assignment.vendor_reviewed_by_id = None

    _refresh_operations_status_after_completion(assignment)
    db.session.commit()

    flash("Job marked complete successfully.", "success")
    return redirect(url_for("vendor_portal.completed_jobs"))


@vendor_portal_bp.route(
    "/jobs/<int:assignment_id>/source-file",
)
@vendor_login_required
def download_source_file(assignment_id):
    vendor = get_current_vendor()
    assignment = _get_vendor_assignment_or_404(
        vendor,
        assignment_id,
    )

    full_path = _safe_static_file(
        assignment.file_path
    )

    if not full_path:
        abort(404)

    download_name = (
        assignment.file_title
        or os.path.basename(full_path)
    )

    return send_file(
        full_path,
        as_attachment=True,
        download_name=download_name,
    )


# ------------------------------------------------------------------
# Vendor Invoice / Payment Portal
# ------------------------------------------------------------------

VENDOR_INVOICE_EXTENSIONS = {".pdf", ".jpg", ".jpeg", ".png"}


def _is_nsez_invoice_branch(branch):
    """Return True when the Crystal Hues billing branch is NSEZ.

    GST must not be added to vendor invoices billed to the NSEZ branch.
    We deliberately identify NSEZ from the branch master instead of vendor
    profile data so the rule remains branch-specific.
    """
    if branch is None:
        return False

    values = (
        getattr(branch, "branch_name", None),
        getattr(branch, "branch_code", None),
        getattr(branch, "tally_company_name", None),
    )
    return any("NSEZ" in str(value or "").strip().upper() for value in values)


def _eligible_customer_invoice(jobcard_id):
    """Latest non-cancelled customer invoice for the jobcard."""
    return (
        Invoice.query
        .filter(
            Invoice.jobcard_id == jobcard_id,
            Invoice.is_cancelled.is_(False),
            Invoice.status != "Cancelled",
        )
        .order_by(Invoice.invoice_date.desc(), Invoice.id.desc())
        .first()
    )


def _assignment_already_vendor_invoiced(assignment_id):
    return (
        VendorInvoiceItem.query
        .filter_by(assignment_id=assignment_id)
        .first()
        is not None
    )


def _ready_to_invoice_rows(vendor):
    completed = (
        _vendor_assignment_query(vendor)
        .filter(OperationsJobcardAssignment.status == "Completed")
        .order_by(
            OperationsJobcardAssignment.completed_at.desc(),
            OperationsJobcardAssignment.id.desc(),
        )
        .all()
    )

    rows = []
    for assignment in completed:
        if _assignment_already_vendor_invoiced(assignment.id):
            continue

        service = assignment.jobcard_service
        jobcard = service.jobcard if service else None
        if not jobcard:
            continue

        customer_invoice = _eligible_customer_invoice(jobcard.id)
        if not customer_invoice:
            continue

        company_branch = customer_invoice.company_branch
        rows.append({
            "assignment": assignment,
            "service": service,
            "jobcard": jobcard,
            "customer_invoice": customer_invoice,
            "company_branch": company_branch,
            "gst_exempt": _is_nsez_invoice_branch(company_branch),
            "amount": _amount_for_assignment(assignment),
        })

    return rows


def _save_vendor_invoice_file(file_obj):
    if not file_obj or not file_obj.filename:
        raise ValueError("Please upload the vendor invoice document.")

    original_name = secure_filename(file_obj.filename)
    if not original_name:
        raise ValueError("Invalid invoice filename.")

    ext = os.path.splitext(original_name)[1].lower()
    if ext not in VENDOR_INVOICE_EXTENSIONS:
        raise ValueError("Invoice document must be PDF, JPG, JPEG or PNG.")

    upload_root = os.path.join(
        current_app.root_path,
        "static",
        "uploads",
        "vendor_invoices",
    )
    os.makedirs(upload_root, exist_ok=True)

    stored_name = f"{uuid.uuid4().hex}{ext}"
    absolute_path = os.path.join(upload_root, stored_name)
    file_obj.save(absolute_path)

    return original_name, f"uploads/vendor_invoices/{stored_name}"


@vendor_portal_bp.route("/invoices/ready", methods=["GET", "POST"])
@vendor_login_required
def ready_to_invoice():
    vendor = get_current_vendor()
    profile = _vendor_profile(vendor, create=False)
    rows = _ready_to_invoice_rows(vendor)
    vendor_currency = (vendor.currency or "").strip().upper()

    if request.method == "POST":
        if not profile or not profile.is_complete:
            flash(
                "You cannot raise an invoice until your billing and payment profile is complete.",
                "danger",
            )
            return redirect(url_for("vendor_portal.my_profile", next=url_for("vendor_portal.ready_to_invoice")))

        if not vendor_currency:
            flash("Your vendor currency is not configured. Please contact the Crystal Nexus team before raising an invoice.", "danger")
            return redirect(url_for("vendor_portal.ready_to_invoice"))

        selected_ids = []
        for value in request.form.getlist("assignment_ids"):
            try:
                selected_ids.append(int(value))
            except (TypeError, ValueError):
                pass
        if not selected_ids:
            flash("Select at least one completed job to raise an invoice.", "warning")
            return redirect(url_for("vendor_portal.ready_to_invoice"))

        invoice_mode = (request.form.get("invoice_mode") or "upload").strip().lower()
        invoice_date_raw = (request.form.get("invoice_date") or "").strip()
        due_date_raw = (request.form.get("due_date") or "").strip()
        try:
            invoice_date = datetime.strptime(invoice_date_raw, "%Y-%m-%d").date()
        except (TypeError, ValueError):
            flash("Please select a valid invoice date.", "danger")
            return redirect(url_for("vendor_portal.ready_to_invoice"))
        try:
            due_date = datetime.strptime(due_date_raw, "%Y-%m-%d").date() if due_date_raw else invoice_date + timedelta(days=30)
        except ValueError:
            flash("Please select a valid due date.", "danger")
            return redirect(url_for("vendor_portal.ready_to_invoice"))
        if due_date < invoice_date:
            flash("Due date cannot be earlier than the invoice date.", "danger")
            return redirect(url_for("vendor_portal.ready_to_invoice"))

        selected_rows = []
        for assignment_id in selected_ids:
            assignment = _get_vendor_assignment_or_404(vendor, assignment_id)
            if assignment.status != "Completed":
                flash("Only completed jobs can be invoiced.", "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            if _assignment_already_vendor_invoiced(assignment.id):
                flash("One of the selected jobs has already been invoiced.", "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            service = assignment.jobcard_service
            jobcard = service.jobcard if service else None
            if not jobcard:
                flash("A selected assignment is missing its jobcard link.", "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            customer_invoice = _eligible_customer_invoice(jobcard.id)
            if not customer_invoice:
                flash(f"{jobcard.jobcard_code} is not eligible because its customer invoice has not been created yet.", "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            selected_rows.append((assignment, service, jobcard, customer_invoice))

        # A vendor invoice is legally branch-specific. The branch comes from the
        # linked CUSTOMER invoice (Crystal Hues invoice branch), never from the
        # vendor or jobcard master. Keep this server-side validation even though
        # the UI also locks selection after the first job is ticked.
        branch_ids = {row[3].company_branch_id for row in selected_rows}
        if None in branch_ids:
            flash(
                "One of the linked customer invoices does not have a Crystal Hues invoice branch. "
                "Please contact Finance before raising this vendor invoice.",
                "danger",
            )
            return redirect(url_for("vendor_portal.ready_to_invoice"))
        if len(branch_ids) != 1:
            branch_names = sorted({
                (row[3].company_branch.branch_name or f"Branch #{row[3].company_branch_id}").strip()
                for row in selected_rows
                if row[3].company_branch
            })
            flash(
                "Selected jobs belong to different Crystal Hues invoice branches"
                + (f" ({', '.join(branch_names)})" if branch_names else "")
                + ". Please raise a separate vendor invoice for each branch.",
                "warning",
            )
            return redirect(url_for("vendor_portal.ready_to_invoice"))
        invoice_branch = selected_rows[0][3].company_branch
        if not (invoice_branch.branch_address or "").strip():
            flash(
                "The selected Crystal Hues invoice branch does not have a full branch address configured. "
                "Please ask Finance/Admin to update the Company Branch master before raising this invoice.",
                "danger",
            )
            return redirect(url_for("vendor_portal.ready_to_invoice"))

        taxable_total = sum((_amount_for_assignment(row[0]) for row in selected_rows), Decimal("0"))
        is_inr = vendor_currency == "INR"
        nsez_gst_exempt = _is_nsez_invoice_branch(invoice_branch)
        gst_applicable = bool(profile.gst_registered and is_inr and not nsez_gst_exempt)

        taxable_total, gst_rate, gst_amount, total = VendorInvoice.calculate_invoice_values(
            taxable_total, vendor_currency, gst_applicable
        )
        tds_rate, tds_amount, net_payable = VendorInvoice.calculate_tds_values(
            total, vendor_currency, taxable_total if gst_applicable else None
        )
        now = _now()

        if invoice_mode == "upload":
            if request.form.get("upload_details_confirm") != "1":
                flash(
                    "Please confirm that your uploaded invoice contains the Crystal Hues branch address, "
                    "your vendor address, PAN/GST details where applicable, and your available bank / PayPal details. "
                    + (
                        "GST must NOT be charged because the selected invoice branch is NSEZ."
                        if nsez_gst_exempt
                        else "GST-registered INR vendors must show 18% GST separately."
                    ),
                    "danger",
                )
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            vendor_invoice_no = (request.form.get("vendor_invoice_no") or "").strip()
            if not vendor_invoice_no:
                flash("Please enter your invoice number.", "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            duplicate = VendorInvoice.query.filter(
                VendorInvoice.vendor_id == vendor.id,
                func.lower(VendorInvoice.vendor_invoice_no) == vendor_invoice_no.lower(),
            ).first()
            if duplicate:
                flash("This invoice number has already been raised in the portal.", "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            try:
                original_name, file_path = _save_vendor_invoice_file(request.files.get("invoice_file"))
            except ValueError as exc:
                flash(str(exc), "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            invoice_source = "UPLOADED"
            signature_name = None
            signature_confirmed_at = None
            signature_ip = None
        elif invoice_mode == "generated":
            signature_name = (request.form.get("signature_name") or "").strip()
            confirmed = request.form.get("signature_confirm") == "1"
            if not signature_name or not confirmed:
                flash("Enter your full name and confirm the electronic signature declaration to generate the invoice.", "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))
            vendor_invoice_no = f"CNVI-{vendor.external_translator_id}-{uuid.uuid4().hex[:8].upper()}"
            original_name = "pending.pdf"
            file_path = "uploads/vendor_invoices/pending.pdf"
            invoice_source = "GENERATED"
            signature_confirmed_at = now
            signature_ip = (request.headers.get("X-Forwarded-For") or request.remote_addr or "")[:64]
        else:
            flash("Please choose a valid invoice creation option.", "danger")
            return redirect(url_for("vendor_portal.ready_to_invoice"))

        invoice = VendorInvoice(
            vendor_id=vendor.id,
            vendor_invoice_no=vendor_invoice_no,
            invoice_date=invoice_date,
            due_date=due_date,
            currency=vendor_currency,
            taxable_amount=taxable_total,
            # This flag means GST is applied on this invoice. Vendor GST
            # registration itself is still preserved separately in
            # vendor_gst_registered by _snapshot_billing_details().
            gst_registered=gst_applicable,
            gst_rate=gst_rate,
            gst_amount=gst_amount,
            total_amount=total,
            tds_rate=tds_rate,
            tds_amount=tds_amount,
            net_payable_amount=net_payable,
            tds_confirmed=False,
            invoice_file_name=original_name,
            invoice_file_path=file_path,
            invoice_source=invoice_source,
            signature_name=signature_name,
            signature_confirmed_at=signature_confirmed_at,
            signature_ip=signature_ip,
            status="RAISED",
            payment_status="Pending",
        )
        _snapshot_billing_details(invoice, profile, invoice_branch)
        db.session.add(invoice)
        db.session.flush()

        for assignment, service, jobcard, customer_invoice in selected_rows:
            db.session.add(VendorInvoiceItem(
                vendor_invoice_id=invoice.id,
                assignment_id=assignment.id,
                customer_invoice_id=customer_invoice.id,
                jobcard_id=jobcard.id,
                jobcard_code=jobcard.jobcard_code,
                service_name=service.service_name,
                quantity=assignment.assigned_qty or 0,
                rate=assignment.rate or 0,
                flat_rate=bool(assignment.flat_rate),
                amount=_amount_for_assignment(assignment),
            ))

        if invoice_mode == "generated":
            try:
                original_name, file_path, _ = generate_system_vendor_invoice_pdf(invoice, selected_rows)
                invoice.invoice_file_name = original_name
                invoice.invoice_file_path = file_path
            except Exception as exc:
                db.session.rollback()
                current_app.logger.exception("Unable to generate system vendor invoice PDF")
                flash(f"The invoice could not be generated: {exc}", "danger")
                return redirect(url_for("vendor_portal.ready_to_invoice"))

        db.session.commit()
        flash(f"Invoice {vendor_invoice_no} raised successfully for {len(selected_rows)} job(s) in {vendor_currency}.", "success")
        return redirect(url_for("vendor_portal.invoice_history"))

    ready_total = sum((row["amount"] for row in rows), Decimal("0"))
    return render_template(
        "vendor_portal/ready_to_invoice.html",
        vendor=vendor,
        rows=rows,
        ready_total=ready_total,
        today=date.today(),
        default_due=date.today() + timedelta(days=30),
        vendor_currency=vendor_currency,
        billing_profile=profile,
        profile_complete=bool(profile and profile.is_complete),
    )


@vendor_portal_bp.route("/invoices")
@vendor_login_required
def invoice_history():
    vendor = get_current_vendor()
    invoices = (
        VendorInvoice.query
        .filter_by(vendor_id=vendor.id)
        .order_by(VendorInvoice.raised_at.desc(), VendorInvoice.id.desc())
        .all()
    )
    return render_template(
        "vendor_portal/invoice_history.html",
        vendor=vendor,
        invoices=invoices,
    )


@vendor_portal_bp.route("/invoices/<int:invoice_id>")
@vendor_login_required
def vendor_invoice_detail(invoice_id):
    vendor = get_current_vendor()
    invoice = VendorInvoice.query.filter_by(
        id=invoice_id,
        vendor_id=vendor.id,
    ).first_or_404()
    return render_template(
        "vendor_portal/invoice_detail.html",
        vendor=vendor,
        invoice=invoice,
    )


@vendor_portal_bp.route("/invoices/<int:invoice_id>/download")
@vendor_login_required
def download_vendor_invoice(invoice_id):
    vendor = get_current_vendor()
    invoice = VendorInvoice.query.filter_by(
        id=invoice_id,
        vendor_id=vendor.id,
    ).first_or_404()

    if invoice.invoice_source == "GENERATED":
        generate_system_vendor_invoice_pdf(invoice, None)

    full_path = _safe_static_file(invoice.invoice_file_path)
    if not full_path:
        abort(404)

    return send_file(
        full_path,
        as_attachment=True,
        download_name=invoice.invoice_file_name,
    )


@vendor_portal_bp.route("/payments")
@vendor_login_required
def payment_status():
    vendor = get_current_vendor()
    invoices = (
        VendorInvoice.query
        .filter_by(vendor_id=vendor.id)
        .order_by(VendorInvoice.invoice_date.desc(), VendorInvoice.id.desc())
        .all()
    )
    return render_template(
        "vendor_portal/payment_status.html",
        vendor=vendor,
        invoices=invoices,
    )
