# ============================================================
# Letter engine: templates -> text -> PDF (reportlab, already used in project)
# ============================================================
from io import BytesIO
from xml.sax.saxutils import escape

from django.core.files.base import ContentFile
from django.utils import timezone
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer

from .common import dept_name, next_seq
from .models import EmployeeLetter

PREFIX = {"APPOINTMENT": "APT", "CONFIRMATION": "CNF", "PROMOTION": "PRM", "RELIEVING_EXPERIENCE": "REL"}

TEMPLATES = {
    "APPOINTMENT": (
        "Appointment Letter - {designation}",
        "Date: {date}\n\nDear {employee_name},\n\n"
        "We are pleased to appoint you as {designation} in the {department} department of {company_name}, "
        "with effect from {joining_date}. Your employee code is {employee_code}.\n\n"
        "Your annual cost to company (CTC) will be Rs. {ctc_annual}, with a basic salary of Rs. {basic_salary} per month, "
        "as detailed in the salary annexure. Your probation period is {probation_period}.\n\n"
        "Your appointment is subject to the company policies, verification of the documents submitted by you and the "
        "terms of employment shared with you.\n\n"
        "We welcome you to {company_name} and look forward to a long and rewarding association."),
    "CONFIRMATION": (
        "Confirmation of Employment",
        "Date: {date}\n\nDear {employee_name},\n\n"
        "We are pleased to inform you that, based on the review of your performance during the probation period, "
        "your services as {designation} ({employee_code}) in the {department} department are confirmed as "
        "permanent with effect from {confirmation_date}.\n\n"
        "All other terms and conditions of your appointment remain unchanged.\n\n"
        "Congratulations and best wishes from {company_name}."),
    "PROMOTION": (
        "Promotion Letter - {new_designation}",
        "Date: {date}\n\nDear {employee_name},\n\n"
        "In recognition of your performance and contribution, you are promoted from {designation} to "
        "{new_designation} with effect from {effective_date}. Your grade/band will be {new_grade}.\n\n"
        "Your compensation will be revised by {hike_percent}%. The revised CTC structure is shared separately.\n\n"
        "Congratulations from all of us at {company_name}."),
    "RELIEVING_EXPERIENCE": (
        "Relieving & Experience Certificate",
        "Date: {date}\n\nTo whom it may concern,\n\n"
        "This is to certify that {employee_name} ({employee_code}) was employed with {company_name} as "
        "{designation} in the {department} department from {joining_date} to {last_working_day}.\n\n"
        "{employee_name} has been relieved from the services of the company at the close of working hours on "
        "{last_working_day}, after completing the exit formalities. During the tenure the conduct of the employee "
        "was found satisfactory.\n\nWe wish {employee_name} all the best for future endeavours."),
}


# ---- ADDITIVE: Document Vault standard letterhead templates (9 cards) ----
PREFIX.update({"OFFER": "OFF", "COMPENSATION_REVISION": "REV", "TRANSFER": "TRF",
               "DISCIPLINARY_WARNING": "DIS", "EXPERIENCE_CERTIFICATE": "EXP"})

TEMPLATES.update({
    "OFFER": (
        "Offer of Employment - {designation}",
        "Date: {date}\n\nDear {employee_name},\n\n"
        "We are delighted to offer you the position of {designation} at {company_name}. Your proposed date of "
        "joining is {joining_date}.\n\n"
        "Your annual cost to company (CTC) will be Rs. {ctc_annual}, as detailed in the CTC annexure attached to "
        "this letter. This offer is valid until {offer_valid_until} and is subject to satisfactory document "
        "verification and background checks.\n\n"
        "Please sign and return a copy of this letter as your acceptance. We look forward to welcoming you to "
        "{company_name}."),
    "COMPENSATION_REVISION": (
        "Annual Compensation Revision - {effective_date}",
        "Date: {date}\n\nDear {employee_name},\n\n"
        "Based on your performance and contribution as {designation} ({employee_code}), your compensation is "
        "revised with effect from {effective_date}.\n\n"
        "Current annual CTC: Rs. {current_ctc}\nRevised annual CTC: Rs. {revised_ctc}\nIncrement: {hike_percent}%\n\n"
        "All other terms of your employment remain unchanged. Thank you for your continued commitment to "
        "{company_name}."),
    "TRANSFER": (
        "Internal Transfer - {employee_name}",
        "Date: {date}\n\nDear {employee_name},\n\n"
        "This is to inform you that you are transferred from the {from_department} department to the "
        "{to_department} department ({to_branch}) with effect from {effective_date}. You will report to "
        "{reporting_manager}.\n\n"
        "Please complete the handover of your current responsibilities before the effective date. All other terms "
        "of your employment remain unchanged."),
    "DISCIPLINARY_WARNING": (
        "Formal Warning - {warning_level}",
        "Date: {date}\n\nDear {employee_name},\n\n"
        "This letter is a formal {warning_level} regarding the following matter noted on {incident_date}: "
        "{warning_reason}.\n\n"
        "You are advised to ensure strict adherence to company policies and attendance norms. Any repetition may "
        "lead to further disciplinary action as per the Code of Conduct of {company_name}."),
    "EXPERIENCE_CERTIFICATE": (
        "Certificate of Experience",
        "Date: {date}\n\nTo whom it may concern,\n\n"
        "This is to certify that {employee_name} ({employee_code}) worked with {company_name} as {designation} "
        "in the {department} department from {joining_date} to {last_working_day}.\n\n"
        "During this tenure the conduct and performance of the employee were found satisfactory. "
        "We wish {employee_name} the very best."),
})

# placeholders available to every template (documented for the UI template editor)
BASE_PLACEHOLDERS = ["date", "company_name", "company_address", "employee_name", "employee_code", "designation",
                     "department", "joining_date", "ctc_annual", "basic_salary", "probation_period",
                     "confirmation_date", "last_working_day"]
EXTRA_PLACEHOLDERS = {
    "OFFER": ["offer_valid_until"],
    "CONFIRMATION": [],
    "PROMOTION": ["new_designation", "new_grade", "hike_percent", "effective_date"],
    "COMPENSATION_REVISION": ["current_ctc", "revised_ctc", "hike_percent", "effective_date"],
    "TRANSFER": ["from_department", "to_department", "to_branch", "reporting_manager", "effective_date"],
    "DISCIPLINARY_WARNING": ["warning_level", "incident_date", "warning_reason"],
}


def resolve_template(company, letter_type):
    """Company override (People.LetterTemplate) if present, else the built-in default."""
    from .models import LetterTemplate
    t = LetterTemplate.objects.filter(company=company, code=letter_type, is_active=True).first()
    d_subject, d_body = TEMPLATES[letter_type]
    if t is None:
        return d_subject, d_body
    return (t.subject or d_subject), (t.body or d_body)


class _Safe(dict):
    def __missing__(self, key):
        return "-"


def build_variables(emp, extra_vars=None):
    co = emp.company
    try:
        comp = emp.compensation_package
    except Exception:
        comp = None
    ctc = None
    if comp is not None:
        ctc = comp.offered_annual_ctc or comp.current_annual_ctc
    if ctc is None and emp.Basic_Salary:
        ctc = emp.Basic_Salary * 12
    try:
        extra = emp.people_profile
    except Exception:
        extra = None
    v = {
        "date": timezone.localdate().strftime("%d %B %Y"),
        "company_name": co.Registered_Company_Name or co.Brand_Name or "the Company",
        "company_address": co.Company_address or "",
        "employee_name": emp.name, "employee_code": emp.employee_code,
        "designation": emp.Designation or "-", "department": dept_name(emp) or "concerned",
        "joining_date": emp.Date_of_Joining.strftime("%d %B %Y") if emp.Date_of_Joining else "-",
        "ctc_annual": f"{ctc:,.0f}" if ctc else "-",
        "basic_salary": f"{emp.Basic_Salary:,.0f}" if emp.Basic_Salary else "-",
        "probation_period": emp.Probation_Period or "as per policy",
        "confirmation_date": (extra.confirmation_date.strftime("%d %B %Y")
                              if extra and extra.confirmation_date else timezone.localdate().strftime("%d %B %Y")),
        "last_working_day": emp.Last_Working_Day or "-",
        "new_designation": "-", "new_grade": "-", "hike_percent": "0", "effective_date": "-",
    }
    for k, val in (extra_vars or {}).items():
        v[k] = val.strftime("%d %B %Y") if hasattr(val, "strftime") else val
    return v


def render_pdf(company_name, company_address, subject, body, letter_no):
    buf = BytesIO()
    doc = SimpleDocTemplate(buf, pagesize=A4, leftMargin=22 * mm, rightMargin=22 * mm,
                            topMargin=20 * mm, bottomMargin=20 * mm, title=subject)
    ss = getSampleStyleSheet()
    head = ParagraphStyle("h", parent=ss["Title"], fontSize=16, alignment=0, spaceAfter=2)
    small = ParagraphStyle("s", parent=ss["Normal"], fontSize=8.5, textColor="#555555")
    body_style = ParagraphStyle("b", parent=ss["Normal"], fontSize=10.5, leading=15, spaceAfter=8)
    sub = ParagraphStyle("sub", parent=ss["Heading3"], fontSize=12, spaceBefore=10, spaceAfter=10)
    story = [Paragraph(escape(company_name), head),
             Paragraph(escape(company_address or "").replace("\n", "<br/>"), small),
             Paragraph(f"Ref: {escape(letter_no)}", small), Spacer(1, 8 * mm),
             Paragraph(escape(subject), sub)]
    for block in body.split("\n\n"):
        story.append(Paragraph(escape(block).replace("\n", "<br/>"), body_style))
    story += [Spacer(1, 16 * mm), Paragraph("Authorised Signatory", body_style),
              Paragraph(f"HR Department, {escape(company_name)}", small)]
    doc.build(story)
    return buf.getvalue()


def issue_letter(company, emp, letter_type, actor, extra_vars=None, subject=None, body=None):
    """Create + render an EmployeeLetter. Custom subject/body override the template."""
    if letter_type not in TEMPLATES:
        raise ValueError(f"Invalid letter_type. Allowed: {', '.join(TEMPLATES)}")
    vars_ = build_variables(emp, extra_vars)
    t_subject, t_body = resolve_template(company, letter_type)      # ADDITIVE: company override aware
    final_subject = (subject or t_subject).format_map(_Safe(vars_))
    final_body = (body or t_body).format_map(_Safe(vars_))
    year = timezone.localdate().year
    letter_no = next_seq(EmployeeLetter, company, "letter_no", f"{PREFIX[letter_type]}-{year}-")
    letter = EmployeeLetter.objects.create(
        company=company, employee=emp, letter_type=letter_type, letter_no=letter_no,
        subject=final_subject, body=final_body, variables={k: str(v) for k, v in vars_.items()},
        issued_by=actor, created_by=actor, updated_by=actor)
    pdf = render_pdf(vars_["company_name"], vars_["company_address"], final_subject, final_body, letter_no)
    letter.pdf_file.save(f"{letter_no}.pdf", ContentFile(pdf), save=True)
    return letter
