# Copyright (c) 2021-2025 Arista Networks, Inc.
# Use of this source code is governed by the MIT license
# that can be found in the LICENSE file.
"""jinja_template_syntax_error_rule.py - Rule class to check that file does not have jinja syntax errors."""

from __future__ import annotations

from typing import Any

import jinja2

from j2lint.linter.error import LinterError
from j2lint.linter.rule import Rule


class JinjaTemplateSyntaxErrorRule(Rule):
    """Rule class to check that file does not have jinja syntax errors."""

    rule_id = "S0"
    description = "Jinja syntax should be correct"
    short_description = "jinja-syntax-error"
    severity = "HIGH"

    def __init__(self, ignore: bool = False, warn: list[Any] | None = None) -> None:
        super().__init__(ignore=ignore, warn=warn)

    def checktext(self, filename: str, text: str) -> list[LinterError]:
        """Check if the given text has jinja syntax error.

        Parameters
        ----------
        filename
            The filename to which the line belongs.
        text
            Entire text content of the file

        Returns
        -------
        list[LinterError]
            The list of LinterError generated by this rule.
        """
        result = []

        env = jinja2.Environment(extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"], autoescape=True)
        try:
            env.parse(text)
        except jinja2.TemplateSyntaxError as error:
            result.append(
                LinterError(
                    error.lineno,
                    text.split("\n")[error.lineno - 1],
                    filename,
                    self,
                    error.message,
                )
            )

        return result

    def checkline(self, filename: str, line: str, line_no: int) -> list[LinterError]:
        """Not Implemented for this rule."""
        raise NotImplementedError
