import json


VERSION = "V1.0-20260828"
QUOTE_DOC_NAME = f"智慧食堂客户方案说明｜{VERSION}.pdf"
PRODUCT_DOC_NAME = f"智慧食堂客户方案说明｜{VERSION}"
PILOT_REF = f"PORTAL-PILOT-{VERSION}"
PILOT_CUSTOMER = f"客户门户验收｜{VERSION}"
PREVIOUS_URL_KEY = "cpt.customer_portal_launch.previous_web_base_url"
PREVIOUS_FREEZE_KEY = "cpt.customer_portal_launch.previous_web_base_url_freeze"
PREVIOUS_LOGO_KEY = "cpt.customer_portal_launch.previous_company_logo"
MISSING = "__MISSING__"


try:
    ICP = env["ir.config_parameter"].sudo()
    previous_url = ICP.get_param(PREVIOUS_URL_KEY)
    previous_freeze = ICP.get_param(PREVIOUS_FREEZE_KEY)
    previous_logo = ICP.get_param(PREVIOUS_LOGO_KEY)
    tracking_keys = ICP.search([("key", "in", [PREVIOUS_URL_KEY, PREVIOUS_FREEZE_KEY, PREVIOUS_LOGO_KEY])])
    if len(tracking_keys) != 3:
        raise RuntimeError("缺少完整回滚基线，停止回滚")

    orders = env["sale.order"].sudo().search([("client_order_ref", "=", PILOT_REF)])
    order_ids = orders.ids
    orders.unlink()

    product_docs = env["product.document"].sudo().search([("name", "=", PRODUCT_DOC_NAME)])
    product_doc_ids = product_docs.ids
    product_docs.unlink()

    quote_docs = env["quotation.document"].sudo().search([("name", "=", QUOTE_DOC_NAME)])
    quote_doc_ids = quote_docs.ids
    quote_docs.unlink()

    partner = env["res.partner"].sudo().search([("name", "=", PILOT_CUSTOMER)], limit=1)
    if partner and not env["sale.order"].sudo().search_count([("partner_id", "=", partner.id)]):
        partner.unlink()

    if previous_url == MISSING:
        ICP.set_param("web.base.url", "http://127.0.0.1:8069")
    elif previous_url:
        ICP.set_param("web.base.url", previous_url)
    if previous_freeze == MISSING:
        ICP.search([("key", "=", "web.base.url.freeze")]).unlink()
    elif previous_freeze:
        ICP.set_param("web.base.url.freeze", previous_freeze)
    if previous_logo == MISSING:
        env.company.sudo().write({"logo": False})
    elif previous_logo:
        env.company.sudo().write({"logo": previous_logo.encode()})
    tracking_keys.unlink()

    env.cr.commit()
    print("ROLLBACK_RESULT", json.dumps({
        "orders": order_ids,
        "product_documents": product_doc_ids,
        "quotation_documents": quote_doc_ids,
        "web_base_url": ICP.get_param("web.base.url"),
        "web_base_url_freeze": ICP.get_param("web.base.url.freeze"),
    }, ensure_ascii=False, sort_keys=True))
except Exception:
    env.cr.rollback()
    raise
