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

from __future__ import annotations

import re

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

_IMPORT_RE   = re.compile(r"^\s*import\s+([\w.*]+)", re.MULTILINE)
_CLASS_RE    = re.compile(r"^(\s*)(?:(?:public|private|protected|internal|abstract|open|sealed|data|enum|annotation|inline|value)\s+)*(?:class|interface|object|enum class|annotation class|data class|sealed class|sealed interface)\s+(\w+)", re.MULTILINE)
_FUN_RE      = re.compile(r"^(\s*)(?:(?:public|private|protected|internal|override|suspend|inline|tailrec|operator|infix|external|abstract|open)\s+)*fun\s+(\w+)\s*[<(]", re.MULTILINE)
_TYPEALIAS_RE = re.compile(r"^\s*typealias\s+(\w+)\s*=", re.MULTILINE)
_COMPANION_RE = re.compile(r"^\s*companion\s+object(?:\s+(\w+))?", re.MULTILINE)


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


def parse_kotlin(file_path: str, content: str) -> ParseResult:
    result = ParseResult(file_path=file_path, language="kotlin")

    for m in _IMPORT_RE.finditer(content):
        path = m.group(1)
        result.dependencies.append(DependencyRecord(
            path=path, type="import", line_number=_ln(content, m.start()),
            is_local=False,
        ))

    for m in _CLASS_RE.finditer(content):
        name = m.group(2)
        # determine kind from the matched text
        matched = m.group(0).lower()
        if "interface" in matched:
            kind = "interface"
        elif "object" in matched:
            kind = "object"
        elif "enum" in matched:
            kind = "enum"
        else:
            kind = "class"
        result.entities.append(EntityRecord(
            name=name, qualified_name=name, type=kind, kind=kind,
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="kotlin",
        ))

    for m in _FUN_RE.finditer(content):
        name = m.group(2)
        result.entities.append(EntityRecord(
            name=name, qualified_name=name, type="function",
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="kotlin",
        ))

    for m in _TYPEALIAS_RE.finditer(content):
        result.entities.append(EntityRecord(
            name=m.group(1), qualified_name=m.group(1), type="type_alias",
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="kotlin",
        ))

    return result
