"""CSS/SCSS/Sass parser — selectors, variables, mixins, keyframes."""

from __future__ import annotations

import re

from codectx.parser.types import EntityRecord, ParseResult

# SCSS/Sass variable: $name: value
_SCSS_VAR_RE  = re.compile(r"^\s*(\$[\w-]+)\s*:", re.MULTILINE)
# CSS custom property: --name: value
_CSS_VAR_RE   = re.compile(r"^\s*(--[\w-]+)\s*:", re.MULTILINE)
# @mixin definition
_MIXIN_RE     = re.compile(r"^\s*@mixin\s+([\w-]+)\s*", re.MULTILINE)
# @keyframes
_KF_RE        = re.compile(r"^\s*@keyframes\s+([\w-]+)", re.MULTILINE)
# @function (SCSS)
_FN_RE        = re.compile(r"^\s*@function\s+([\w-]+)\s*\(", re.MULTILINE)
# Selectors: class, id, or element followed by {
_SELECTOR_RE  = re.compile(r"^((?:[.#]?[\w-]+(?:\s*[>,+~]\s*[.#]?[\w-]+)*\s*)+)\s*\{", re.MULTILINE)


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


def parse_css(file_path: str, content: str) -> ParseResult:
    result = ParseResult(file_path=file_path, language="css")

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

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

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

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

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

    for m in _SELECTOR_RE.finditer(content):
        selector = m.group(1).strip()
        if not selector or selector.startswith("//"):
            continue
        result.entities.append(EntityRecord(
            name=selector, qualified_name=selector, type="selector",
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()), language="css",
        ))

    return result
