"""One-off generator for the HDFC UAT checklist review Word document."""
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Cm, Pt, RGBColor

OUT = r"f:\xampp\htdocs\courierconnect\HDFC_Bank_UAT_Checklist_Review.docx"

NAVY = RGBColor(0x1A, 0x1A, 0x2E)
MUTED = RGBColor(0x4A, 0x55, 0x68)
YES = RGBColor(0x1B, 0x7A, 0x3A)
NO = RGBColor(0xB0, 0x2A, 0x2A)
PARTIAL = RGBColor(0x8A, 0x5A, 0x00)


def shade(cell, hex_color):
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    shd = OxmlElement("w:shd")
    shd.set(qn("w:fill"), hex_color)
    shd.set(qn("w:val"), "clear")
    tcPr.append(shd)


def set_run_font(run, size=11, bold=False, color=None):
    run.font.name = "Calibri"
    run._element.rPr.rFonts.set(qn("w:eastAsia"), "Calibri")
    run.font.size = Pt(size)
    run.bold = bold
    if color is not None:
        run.font.color.rgb = color


def answer_color(text):
    low = text.lower().strip()
    if "partial" in low or low.startswith("cannot") or ("yes for" in low and "no for" in low):
        return PARTIAL
    if low.startswith("yes") or low.startswith("process answer: yes"):
        return YES
    if low.startswith("no") or low.startswith("not in"):
        return NO
    return None


def add_table(doc, headers, rows, col_widths):
    table = doc.add_table(rows=1, cols=len(headers))
    table.style = "Table Grid"
    table.autofit = False
    hdr = table.rows[0].cells
    for i, title in enumerate(headers):
        hdr[i].text = ""
        p = hdr[i].paragraphs[0]
        run = p.add_run(title)
        set_run_font(run, 11, True, RGBColor(255, 255, 255))
        shade(hdr[i], "1A1A2E")
        hdr[i].width = col_widths[i]
    for r_i, row in enumerate(rows):
        cells = table.add_row().cells
        bg = "F7F8FA" if r_i % 2 == 0 else "FFFFFF"
        for i, value in enumerate(row):
            cells[i].text = ""
            lines = value.split("\n")
            for line_i, line in enumerate(lines):
                p = cells[i].paragraphs[0] if line_i == 0 else cells[i].add_paragraph()
                run = p.add_run(line)
                color = answer_color(line)
                set_run_font(run, 10.5, bold=(color is not None), color=color)
                p.paragraph_format.space_after = Pt(0)
                p.paragraph_format.space_before = Pt(0)
            shade(cells[i], bg)
            cells[i].width = col_widths[i]
    doc.add_paragraph()
    return table


def heading(doc, text):
    p = doc.add_paragraph()
    p.paragraph_format.space_before = Pt(14)
    p.paragraph_format.space_after = Pt(6)
    run = p.add_run(text)
    set_run_font(run, 16, True, NAVY)


def body(doc, text):
    p = doc.add_paragraph()
    p.paragraph_format.space_after = Pt(6)
    run = p.add_run(text)
    set_run_font(run, 11, False, RGBColor(0x2D, 0x37, 0x48))
    return p


def bullet(doc, text):
    p = doc.add_paragraph(style="List Bullet")
    p.clear()
    run = p.add_run(text)
    set_run_font(run, 11, False, RGBColor(0x2D, 0x37, 0x48))


def main():
    doc = Document()
    section = doc.sections[0]
    section.top_margin = Cm(1.6)
    section.bottom_margin = Cm(1.6)
    section.left_margin = Cm(1.7)
    section.right_margin = Cm(1.7)

    title = doc.add_paragraph()
    title.alignment = WD_ALIGN_PARAGRAPH.LEFT
    run = title.add_run("HDFC Bank UAT Checklist Review")
    set_run_font(run, 22, True, NAVY)

    sub = doc.add_paragraph()
    run = sub.add_run("S and J Group  |  Account Id SG3925  |  Smart Gateway (SG)")
    set_run_font(run, 12, False, MUTED)

    meta = doc.add_paragraph()
    run = meta.add_run("Prepared for internal discussion with the manager. Code was reviewed only. No application code was changed.")
    set_run_font(run, 11, False, MUTED)

    body(
        doc,
        "This note answers the HDFC Bank letter item by item against the current Courier Connect payment flow. "
        "Use the Yes / Partial / No answers when replying to the bank.",
    )

    heading(doc, "1. Bank conditions")
    add_table(
        doc,
        ["Item", "Answer", "What the code does"],
        [
            [
                "Unique customer id for each customer",
                "Partial",
                "Shipment, additional charge, and assisted purchase send CUST_ plus the user id. Membership fee and membership change do not send a customer id. Those payments get a new random id each time, so it is not a stable id for that customer.",
            ],
            [
                "Do not use UDF2",
                "Yes",
                "UDF2 is not sent anywhere.",
            ],
            [
                "Order number and amount on the response page must match the HDFC payment page",
                "No",
                "A success message is shown. Amount is shown for membership and shipment. The order number is not shown on any response page. Shipment shows the tracking number. Assisted purchase shows neither the amount nor the order number.",
            ],
            [
                "Response page must show order number, amount, and success message",
                "Partial",
                "Success message is shown. Order number is not shown.",
            ],
        ],
        [Cm(5.2), Cm(2.4), Cm(9.4)],
    )

    heading(doc, "2. Order ID format")
    body(
        doc,
        "Bank rules: under 21 characters, no special characters, letters and numbers only, and not sequential.",
    )
    add_table(
        doc,
        ["Flow", "Current format", "Result"],
        [
            ["Membership", "receipt_ + payment id", "Contains _. The id increases in sequence."],
            ["Membership change", "MEMCHG- + id + - + time", "Contains -. Length often reaches 21 or more. Sequential."],
            ["Shipment", "SHP_ + id + _ + time", "Contains _. Length can reach 21 or more when the id grows. Sequential."],
            ["Additional charge", "ADD_ + id + _ + time", "Same problem."],
            ["Assisted purchase", "APR_ + id + _ + time", "Same problem."],
            ["Fallback when no receipt is passed", "TXN_ + time + _ + random", "23 characters. Contains _."],
        ],
        [Cm(5.4), Cm(5.6), Cm(6.0)],
    )
    p = doc.add_paragraph()
    run = p.add_run("Order ID format: No. ")
    set_run_font(run, 11, True, NO)
    run = p.add_run("Each attempt gets a different id, but it does not meet all four bank rules.")
    set_run_font(run, 11)

    heading(doc, "3. Security audit confirmation")
    add_table(
        doc,
        ["No.", "Question", "Answer"],
        [
            ["1", "Transaction details and status are stored in the database", "Yes"],
            ["2", "Service is given based on the database status", "Yes"],
            ["3", "Multiple test amounts / links are available", "Yes. Different plan, shipment, additional charge, and assisted purchase amounts."],
            ["4", "Login will remain available until the audit is finished", "Not in the code. A test user and password must be shared separately."],
            ["5", "Do not clear records until the audit is finished", "Process answer: Yes, to be confirmed by the team. The payment flow does not delete these records by itself."],
            ["6", "UAT setup is identical to production", "Cannot be confirmed from code alone. The site URL is https://kurigo.in. The gateway default is the HDFC UAT address."],
            ["7", "Status API (dual inquiry) on the response", "Yes. Order Status API is called before a payment is marked successful. The response is written to the log."],
            ["8", "Audit checklist", "Partial. See section 4."],
        ],
        [Cm(1.4), Cm(9.2), Cm(6.4)],
    )

    heading(doc, "4. Bank checklist")
    add_table(
        doc,
        ["No.", "Item", "Answer"],
        [
            ["1", "Unique order ID", "Yes for uniqueness (a different id per attempt). No for the bank format rules."],
            ["2", "Request tampering — amount taken from the database", "Yes. The amount sent by the browser is not used."],
            ["3", "Response tampering — encrypted response checked against the current session / order id", "Yes. Signature, session id, order id, and Status API are checked. Success is not taken from the redirect parameters."],
            ["4", "URL redirection validation", "Yes. Return URLs are server routes. A payment link is rejected if it points back to the response page."],
            ["5", "Duplicate entry validation", "Yes. A payment that is already successful is not processed again. A failed payment cannot be turned into success through the redirect."],
            ["6", "Receipt generation", "Partial. A confirmation page exists. There is no receipt that shows the order number."],
            ["7", "Valid and secure SSL", "Yes. The site URL is https://kurigo.in."],
        ],
        [Cm(1.4), Cm(8.6), Cm(7.0)],
    )

    heading(doc, "5. Values for the bank form")
    add_table(
        doc,
        ["Field", "Value"],
        [
            ["MERCHANT NAME", "S and J Group"],
            ["Account Id", "SG3925"],
            ["WEBSITE URL", "https://kurigo.in"],
            ["Website publicly accessible", "Yes"],
            ["LOGIN ID / PASSWORD", "Not in the code. A UAT test login must be provided separately."],
            [
                "RESPONSE URL",
                "https://kurigo.in/payment/response/membership\nhttps://kurigo.in/payment/response/shipment\nhttps://kurigo.in/payment/response/assisted-purchase\nhttps://kurigo.in/payment/hdfc/response",
            ],
            ["DEVELOPER CONTACT / EMAIL", "Not in the code."],
            ["TYPE", "SG"],
            ["Programming Language", "PHP (Laravel)"],
            ["Plugin", "None. Custom HDFC Smart Gateway integration."],
            ["Transaction flow verified", "The bank has already marked this Yes."],
            ["Multiple amount values", "Yes"],
            ["Transaction response stored in the database, including failed", "Yes"],
        ],
        [Cm(7.2), Cm(9.8)],
    )

    heading(doc, "6. Points to raise with the manager")
    bullet(doc, "The Status API response is written in storage/logs/laravel.log under HDFC Order Status API response. The bank has asked for those logs.")
    bullet(doc, "The bank says not to honor orders created during testing. The current code activates membership and marks a shipment as paid when the gateway returns success. Test orders should not be treated as real service.")
    bullet(doc, "The items to answer No to the bank are the order ID format, a stable customer id on membership payments, and the order number on the response page. The other security checks are Yes.")

    heading(doc, "7. Suggested reply stance")
    body(doc, "Safe to confirm as Yes: database storage of success and failed payments, service based on database status, Status API before success, amount taken from the database, response and redirect checks, duplicate protection, UDF2 not used, HTTPS site, multiple amount values, PHP Laravel custom integration, no plugin.")
    body(doc, "Do not confirm as fully done: order ID length / special characters / non-sequential rule, stable customer id on membership fee and membership change, order number on every response page, and a receipt that shows the order number.")

    doc.save(OUT)
    print(OUT)


if __name__ == "__main__":
    main()
