#!/usr/bin/env python3
# ollie:parallel read
# args_json: {"type":"object","required":["path","line","col"],"properties":{"path":{"type":"string","description":"Absolute file path"},"line":{"type":"string","description":"Line number (1-indexed)"},"col":{"type":"string","description":"Column number (1-indexed)"}}}
# ollie:prompt
# ## lsp_completion
#
# Completion candidates at cursor position.
#
# **Args**: `[path, line, col]`
#
# ```
# lsp_completion(path="/abs/path.go", line="42", col="10")
# ```
#
# **Returns**: up to 20 candidates.
# ollie:end

import os
import sys
sys.path.insert(0, os.environ.get('OLLIE_TOOLS_PATH', os.path.dirname(os.path.abspath(__file__))))

from _lib.args import parse_args
from _lib.lsp.client import request

args = parse_args()
filepath = os.path.abspath(args.require("path"))
line = int(args.require("line")) - 1
col = int(args.require("col")) - 1

result = request("completion", file=filepath, line=line, col=col)

if not result:
    sys.exit(0)

items = result.get("items", result) if isinstance(result, dict) else result
if not isinstance(items, list):
    sys.exit(0)

for item in items[:20]:
    label = item.get("label", "")
    detail = item.get("detail", "")
    if detail:
        print(f"{label}\t{detail}")
    else:
        print(label)
