#!/usr/bin/env python3
"""Hotfix v4928.1.5.92: define customer_column in list_tasks().

The deployed task list query is an f-string using o.{customer_column}, but
list_tasks() did not initialise customer_column. This caused /tasks and
/tasks/partials/list to crash with NameError.
"""
from __future__ import annotations

from pathlib import Path

PATH = Path("app/task_service.py")
MARKER = "# v4928.1.5.92: choose schema-supported opportunity customer for task list."
BLOCK = f'''    try:\n        from app.infra.schema_compat import opportunity_customer_column\n        customer_column = opportunity_customer_column()\n    except Exception:\n        customer_column = "local_customer_id"\n    if customer_column not in {{"local_customer_id", "fiscal_customer_id"}}:\n        customer_column = "local_customer_id"\n    {MARKER}\n\n'''


def main() -> int:
    text = PATH.read_text(encoding="utf-8")
    start = text.find("def list_tasks(\n")
    if start < 0:
        raise SystemExit("def list_tasks not found")
    end = text.find("\ndef get_task(", start)
    if end < 0:
        raise SystemExit("def get_task not found after list_tasks")
    body = text[start:end]

    if MARKER in body or "customer_column = opportunity_customer_column()" in body:
        print("already_patched=True")
        return 0

    needle = "    sql = text(f\"\"\"\n        SELECT"
    idx_in_body = body.find(needle)
    if idx_in_body < 0:
        raise SystemExit("list_tasks SQL anchor not found")

    insert_at = start + idx_in_body
    new_text = text[:insert_at] + BLOCK + text[insert_at:]

    backup = PATH.with_suffix(PATH.suffix + ".bak_v4928_1_5_92")
    if not backup.exists():
        backup.write_text(text, encoding="utf-8")
    PATH.write_text(new_text, encoding="utf-8")
    print("patched=True")
    print(f"backup={backup}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
