"""Care HCM help knowledge base for the in-app assistant (answers 'how do I...' questions about every feature)."""
KB = [
 (["check in", "check-in", "checkin", "punch in", "clock in", "mark attendance", "check out", "check-out", "checkout", "punch out", "clock out"],
  "Use the Check In / Check Out button on your Dashboard banner (the same button works for both). The time is taken from the server in Pakistan Standard Time, not from your device. Check-in after the shift start plus the grace period is marked Late; working fewer than the half-day hours is marked Half Day.", "dashboard"),
 (["fingerprint", "biometric", "face id", "windows hello", "touch id", "scanner", "finger print"],
  "Fingerprint check-in: open My Account & Security (blue circle, top right) > Enable on this device. After that, Check In / Check Out asks for your fingerprint, face or screen lock automatically. Devices without it use the normal check-in. If your admin set it to Required, supported devices must use it. It needs the HTTPS address, and you enable it once per device.", "account"),
 (["late", "grace", "half day", "half-day", "shift"],
  "Late = you check in after your shift start plus the grace minutes. Half Day = you worked fewer than the company's half-day hours. A set number of lates (default 3) equals one day's deduction in payroll. HR sets these rules under Settings; your shift times are on your employee profile.", "settings"),
 (["forgot", "forgot to check", "forgot to punch", "missed check", "missed", "missing punch", "correction", "regularize", "regularise", "fix attendance", "wrong attendance"],
  "Forgot to check in or out? Open Time & Leave > Corrections, add the date and the real in/out times with a reason. Your manager or HR approves it and your attendance is corrected automatically.", "m:regularizations"),
 (["my attendance", "attendance history", "monthly attendance", "attendance report"],
  "Time & Leave > Attendance shows your month day by day (status, in, out and how you checked in). Managers can switch to anyone in their team; HR can open anyone. HR can also export a monthly attendance CSV from Reports.", "attendance"),
 (["team calendar", "who is present", "who is absent", "team attendance"],
  "Time & Leave > Team Calendar shows a month grid for your team: P present, L late, H half day, V leave, A absent. Managers see everyone below them; HR sees everyone.", "team_calendar"),
 (["daily attendance", "edit attendance", "change attendance"],
  "HR / Admin: Time & Leave > Daily Attendance lets you pick a date and correct status and times for any employee.", "attendance_day"),
 (["overtime", "ot hours", "extra hours"],
  "Overtime is paid only for employees marked 'Eligible for overtime' on their profile. Hours worked beyond the shift length are paid at the hourly rate times the overtime multiplier set in Settings (default 1.5) and appear on the payslip.", None),
 (["apply leave", "apply for leave", "request leave", "take leave", "day off", "vacation", "sick leave", "annual leave", "casual leave"],
  "Time & Leave > Leave > Apply for leave: choose the type and dates and submit. Weekends and holidays are not counted. Your manager (or anyone above you in the reporting line) and HR can approve it, and you see the status on the same page. You can cancel while it is Pending.", "leave"),
 (["approve leave", "reject leave", "leave approval", "pending leave"],
  "Open Time & Leave > Leave. Requests from people below you in the reporting line appear under 'Waiting for your approval' with Approve and Reject buttons. HR and Admin see all requests.", "leave"),
 (["leave balance", "leaves left", "how many leaves", "leave types", "unpaid leave"],
  "Your balance per leave type is on the Dashboard and on the Leave page. Allowances per year and which types are paid are set by the admin in Settings > Leave types. Unpaid leave reduces salary in payroll.", "leave"),
 (["holiday", "public holiday", "weekly off", "weekend"],
  "Holidays are listed under Time & Leave > Holidays (HR adds them). Holidays and weekly off days are not counted as working days, absences or leave days. Weekly off days are set in Settings.", "holidays"),
 (["payslip", "pay slip", "salary slip", "my salary", "download payslip", "print payslip"],
  "Open the blue circle (top right) > My Profile & Payslips and click View next to the month. Payslips appear after HR finalizes the month. Use Print / Save as PDF on the payslip page.", None),
 (["run payroll", "generate payroll", "process payroll", "payroll run", "finalize payroll", "finalise"],
  "HR / Admin: Pay > Payroll > choose the month > Generate payroll. Review the draft (absences, late deductions, overtime, incentives, loans, reimbursements), add a bonus or other deduction per person, use Recalculate after fixing attendance, then Finalize. Employees only see payslips after Finalize. Export CSV for bank transfers.", "payroll"),
 (["how is salary calculated", "how is net salary calculated", "how is my salary calculated", "salary calculation", "calculated", "deduction", "absent deduction", "net pay", "net salary"],
  "Net pay = gross (basic + allowances) + overtime + productivity incentive + approved expense reimbursements + bonus - absent/unpaid-day deduction - late deduction - tax - provident fund - fixed deduction - loan installment - other deduction. A day's pay is gross divided by the days in the month.", None),
 (["tax", "slab", "income tax", "provident", "pf "],
  "Admin: Settings has a flat tax % and provident fund %. For progressive tax enter slabs as annual_limit:rate pairs, for example 600000:0,1200000:5,999999999:20. Confirm the rates with your accountant before real payroll.", "settings"),
 (["expense", "reimburse", "claim", "receipt"],
  "Pay > Expenses > Add new: enter date, category, amount and description. Your manager or HR approves it; approved claims are paid back in the next payroll and marked Reimbursed when payroll is finalized.", "m:expenses"),
 (["loan", "advance", "installment", "salary advance"],
  "Pay > Loans & Advances > Add new: enter the amount and the monthly installment. After approval the installment is deducted automatically in each payroll until the balance reaches zero.", "m:loans"),
 (["bonus", "incentive", "target", "productivity incentive"],
  "Productivity incentive: set a daily target and an incentive rate per unit on the employee profile. Units above target (claims + A/R + charts + calls logged) are paid at that rate in payroll. HR can also add a one-off bonus on a draft payroll.", "productivity"),
 (["add employee", "new employee", "create employee", "register employee", "onboard employee"],
  "HR / Admin: People > Directory > + Add employee (or Users > Add user with 'Create a new employee profile'). Fill in details, hierarchy level, department, reports-to and salary. Tick 'Create a login' to give them access; you can type a temporary password or leave it empty to auto-generate one.", "employee_new"),
 (["create user", "new user", "add user", "create login", "new login", "temporary password", "temp password", "reset password", "forgot password", "password reset", "change password"],
  "HR / Admin: Admin > Users > Add user. Enter username (work email), role, and either create a new employee profile, link an existing employee, or make a login-only account. Type a temporary password or click Generate; the user must change it at first login. To reset one, use Reset password on the Users page. Your own password: blue circle > My Account & Security.", "users"),
 (["role", "roles", "who can see", "permission", "access right", "access rights", "menu access", "restrict", "super admin", "superadmin", "admin role", "give access", "access to", "grant", "allow user", "deny", "no access", "access denied", "cannot open", "can't open", "403"],
  "Roles: Super Admin, Admin, HR, Manager / Team lead, Employee. Admin > Access Rights lets Admin/Super Admin choose which menus and settings each role can open, or allow/deny a single user. Only a Super Admin can create or change Admins.", "access"),
 (["hierarchy", "level", "reports to", "report to", "manager", "reporting line", "team structure", "who sees my team", "who can see my team", "see my team", "my team"],
  "Each profile has a level (CEO, COO, CHRO, VP, Director, Assistant Director, Senior Manager, Manager, Assistant Manager, Supervisor, Team Lead, Representative) and a Reports to field. You see yourself and everyone below you in the reporting line; HR, Admin and Super Admin see the whole organization.", "org"),
 (["org chart", "organization chart", "organisation chart", "organogram"],
  "People > Org Chart shows the reporting tree with level badges. You see your own line (you and everyone below); HR and Admin see the whole organization.", "org"),
 (["directory", "employee list", "find employee", "search employee"],
  "People > Directory lists employees you are allowed to see (search by name, code or email, filter by department). Click a name for the profile.", "employees"),
 (["deactivate", "resign", "leaving", "offboard", "terminate", "exit"],
  "HR / Admin: open the employee profile > Edit > set Status to Inactive. Their login is disabled and an offboarding checklist (assets, access, exit interview, settlement) is created under People > Onboarding.", "m:onboarding"),
 (["recruit", "hiring", "candidate", "applicant", "job opening", "interview"],
  "People > Recruitment tracks applicants: add a candidate, move them through Applied, Screening, Interview, Offer, Hired. On Hired, click 'Hire → employee' to create the employee record and start onboarding.", "m:candidates"),
 (["onboarding", "checklist", "new joiner", "joining"],
  "People > Onboarding shows checklists for new joiners (documents, accounts, equipment, training, introductions, payroll setup) created automatically when an employee is added, and offboarding tasks for leavers. Mark tasks In progress / Done.", "m:onboarding"),
 (["asset", "laptop", "headset", "equipment", "device issued"],
  "HR / Admin: People > Assets records laptops, headsets and equipment, who they are assigned to, and their status.", "m:assets"),
 (["document", "upload", "contract", "certificate", "cnic", "id card"],
  "Compliance > Documents: upload PDFs, images, Word or Excel files (max 5 MB) with a category and optional expiry date. Files are stored privately; only the owner, their managers and HR can open them. Expiring documents show on the HR dashboard.", "documents"),
 (["policy", "policies", "acknowledge", "code of conduct"],
  "Compliance > Policies: read each policy and click 'I have read and agree'. HR publishes policies and can see who has not yet acknowledged them.", "policies"),
 (["training", "hipaa", "certification", "certificate expiry", "compliance training"],
  "Compliance > Training & Certs records trainings (HIPAA awareness, compliance, coding certificates) with completion and expiry dates. Status shows Valid, Expiring (30 days) or Expired, and the HR dashboard shows company-wide HIPAA compliance.", "m:trainings"),
 (["goal", "kpi", "objective", "okr"],
  "Performance > Goals & KPIs: add a goal with a measure and target date, then update progress and status. Managers and HR can update goals for their people.", "m:goals"),
 (["review", "appraisal", "rating", "performance review", "evaluation"],
  "Performance > Reviews: managers and HR add a review per period with 1-5 ratings for quality, productivity, teamwork and compliance. The overall score is the average, and employees can see their own reviews.", "m:reviews"),
 (["log productivity", "productivity", "claims billed", "daily output", "quality score", "qa score"],
  "Performance > Productivity: log your day (claims billed, A/R accounts worked, charts coded, calls, QA score). Managers see their team's totals, averages and targets, and the monthly top performers chart.", "productivity"),
 (["dialer", "call", "phone", "dial", "call log"],
  "Performance > Dialer: enter or pick a number and press the green call button; it opens your phone app, Teams or softphone. Press the red button when the call ends to log outcome and notes. Each logged call adds 1 to your daily calls in Productivity. Save frequent numbers under My contacts.", "dialer"),
 (["helpdesk", "ticket", "raise issue", "complaint", "ask hr"],
  "Support > HR Helpdesk: open a ticket with a category and details. HR replies and changes the status (Open, In progress, Resolved). You can also ask me quick questions.", "m:tickets"),
 (["announcement", "notice", "news"],
  "Support > Announcements shows company notices; HR posts them. The newest also appear on your Dashboard.", "announcements"),
 (["report", "export", "csv", "download data", "analytics", "chart", "dashboard"],
  "HR / Admin: Admin > Reports has a daily attendance chart, a monthly attendance table, leave usage and CSV export. The Dashboard shows live headcount, attendance, salary and payroll charts, smart insights, top performers and alerts. Payroll can be exported as CSV from the payroll run.", "reports"),
 (["insight", "alert", "smart"],
  "Smart insights on the HR dashboard are automatic checks on your own data: repeated lateness, high absence, missed check-outs, low output against target, payroll changes, leave requests waiting too long and expired training.", "dashboard"),
 (["setting", "settings", "timezone", "time zone", "company rules", "currency"],
  "Admin: Admin > Settings holds company name, timezone (Asia/Karachi), currency, grace period, late rule, half-day hours, tax and PF, overtime multiplier, fingerprint mode, weekly off days, departments and leave types.", "settings"),
 (["two factor", "2fa", "authenticator", "two-step", "2 step", "otp", "verification code", "mfa"],
  "Blue circle > My Account & Security > Two-factor authentication > Set up. Add the key to Google or Microsoft Authenticator, enter the 6-digit code to confirm, and you will be asked for a code at every sign-in. Turn it off with your password.", "account"),
 (["audit", "log of changes", "who changed"],
  "Admin: Admin > Audit Log lists logins, salary and profile edits, role changes, payroll actions, document access and access-rights changes with user and time.", "audit_log"),
 (["install", "mobile", "phone app", "pwa", "home screen", "offline"],
  "Care HCM works in any browser. On a phone or laptop choose 'Install app' / 'Add to Home Screen' for an app-like icon. The menu opens with the ☰ button on small screens.", None),
 (["profile photo", "profile picture", "upload photo", "change photo", "my photo", "picture", "avatar", "photo"],
  "Profile photos: open your profile (blue circle > My Profile & Payslips) and click the camera button on your picture to upload one. HR / Admin can also add a photo when creating or editing an employee (Add employee, Users > Add user, or Edit profile). Photos are cropped to a square automatically and appear in the org chart, team lists, directory, leave approvals and recognition wall, next to the name and designation.", "org"),
 (["backup", "data safe", "security", "privacy", "secure"],
  "Data is stored in your own hosting. Passwords are hashed, sessions are protected, sensitive actions are logged, and access is limited by role, reporting line and your access rights. Admins should download data/hcm.db and data/uploads weekly as a backup.", None),
 (["contact", "support", "help", "problem", "not working", "error", "bug"],
  "For HR questions open a ticket in Support > HR Helpdesk. For technical problems contact your administrator or Code Care MB at Info@codecaremb.com or (409) 916-8949.", "m:tickets"),
 (["what can you do", "what is care hcm", "features", "modules", "overview", "everything"],
  "Care HCM covers: employee directory and org chart, hierarchy-based teams, recruitment and onboarding, attendance with fingerprint check-in, leave, payroll with overtime, incentives, loans and expenses, productivity and KPIs, goals and reviews, training and HIPAA tracking, documents and policies, helpdesk, assets, dialer, reports, audit log and access rights. Ask me 'how do I ...' about any of them.", None),
]
GREET = ["hi", "hello", "hey", "salam", "assalam", "good morning", "good evening"]


import re


def answer(text):
    raw = (text or "").lower()
    if any(p in raw for p in ("what can you do", "what do you do", "what you can do", "what is care hcm", "what can i ask")):
        for ph, ans, link in KB:
            if "what can you do" in ph:
                return ans, link
    t = " " + re.sub(r"\b(a|an|the|my|our|please|can|you|i|we)\b", " ", (text or "").lower().replace("?", " ").replace(".", " ")).strip() + " "
    t = re.sub(r"\s+", " ", t)
    if any(t.strip() == g or t.startswith(" " + g + " ") for g in GREET):
        return "Hello! Ask me how to do anything in Care HCM: check in, apply for leave, run payroll, add an employee, set access rights, and more.", None
    if any(w in t for w in ("thank", "shukria", "thanks")):
        return "You're welcome! Anything else I can help with?", None
    best, score = None, 0
    for phrases, ans, link in KB:
        sc = sum(len(p) for p in phrases if p in t)
        if sc > score:
            best, score = (ans, link), sc
    if best:
        return best
    return ("I couldn't find that. Try asking about: check in, fingerprint, leave, payroll, payslip, expenses, loans, adding employees, users and passwords, access rights, hierarchy, "
            "org chart, recruitment, onboarding, documents, policies, training, goals, reviews, productivity, dialer, reports, settings or two-factor sign-in."), None
