"""HCL/Terraform parser — resources, variables, outputs, modules, data blocks."""

from __future__ import annotations

import re

from codectx.parser.types import EntityRecord, ParseResult

# resource "type" "name" {
_RESOURCE_RE  = re.compile(r'^resource\s+"([\w-]+)"\s+"([\w-]+)"\s*\{', re.MULTILINE)
# variable "name" {
_VARIABLE_RE  = re.compile(r'^variable\s+"([\w-]+)"\s*\{', re.MULTILINE)
# output "name" {
_OUTPUT_RE    = re.compile(r'^output\s+"([\w-]+)"\s*\{', re.MULTILINE)
# module "name" {
_MODULE_RE    = re.compile(r'^module\s+"([\w-]+)"\s*\{', re.MULTILINE)
# data "type" "name" {
_DATA_RE      = re.compile(r'^data\s+"([\w-]+)"\s+"([\w-]+)"\s*\{', re.MULTILINE)
# local.name = ...
_LOCAL_RE     = re.compile(r'^locals\s*\{', re.MULTILINE)
# provider "name"
_PROVIDER_RE  = re.compile(r'^provider\s+"([\w-]+)"\s*\{', re.MULTILINE)
# terraform block
_TERRAFORM_RE = re.compile(r'^terraform\s*\{', re.MULTILINE)


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


def parse_hcl(file_path: str, content: str) -> ParseResult:
    result = ParseResult(file_path=file_path, language="hcl")

    for m in _RESOURCE_RE.finditer(content):
        qname = f"{m.group(1)}.{m.group(2)}"
        result.entities.append(EntityRecord(
            name=m.group(2), qualified_name=qname, type="resource", kind=m.group(1),
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="hcl",
        ))

    for m in _VARIABLE_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="hcl",
        ))

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

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

    for m in _DATA_RE.finditer(content):
        qname = f"data.{m.group(1)}.{m.group(2)}"
        result.entities.append(EntityRecord(
            name=m.group(2), qualified_name=qname, type="data_source", kind=m.group(1),
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="hcl",
        ))

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

    return result
