"""Lua source parser (regex-based)."""

from __future__ import annotations

import re

from codectx.parser.types import DependencyRecord, EntityRecord, ParseResult

_REQUIRE_RE = re.compile(r"""(?:require|dofile|loadfile)\s*[\("]([^)"']+)[)"']""", re.MULTILINE)
_FN_RE      = re.compile(r"^(\s*)function\s+([\w.:]+)\s*\(", re.MULTILINE)
_LOCAL_FN_RE = re.compile(r"^(\s*)local\s+function\s+(\w+)\s*\(", re.MULTILINE)
_TABLE_RE   = re.compile(r"^(\w+)\s*=\s*\{", re.MULTILINE)
_LOCAL_VAR_RE = re.compile(r"^\s*local\s+(\w+)\s*=\s*\{", re.MULTILINE)


def _ln(content: str, pos: int) -> int:
    return content[:pos].count("\n") + 1


def parse_lua(file_path: str, content: str) -> ParseResult:
    result = ParseResult(file_path=file_path, language="lua")

    for m in _REQUIRE_RE.finditer(content):
        path = m.group(1).strip()
        result.dependencies.append(DependencyRecord(
            path=path, type="require", line_number=_ln(content, m.start()),
            is_local=not path.startswith("socket") and "." not in path.split("/")[0],
        ))

    seen: set[str] = set()
    for m in _FN_RE.finditer(content):
        name = m.group(2)
        if name not in seen:
            seen.add(name)
            result.entities.append(EntityRecord(
                name=name.split(".")[-1].split(":")[-1],
                qualified_name=name,
                type="function",
                start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
                language="lua",
            ))
    for m in _LOCAL_FN_RE.finditer(content):
        name = m.group(2)
        if name not in seen:
            seen.add(name)
            result.entities.append(EntityRecord(
                name=name, qualified_name=name, type="function",
                start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
                language="lua",
            ))

    for m in _TABLE_RE.finditer(content):
        name = m.group(1)
        if not name[0].isupper():
            continue
        result.entities.append(EntityRecord(
            name=name, qualified_name=name, type="table",
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="lua",
        ))

    return result
