"""
@RAG_CONTEXT
{
  "archivo": "src/rag_indexer/file_parser.py",
  "lineas": 50,
  "tokens_estimados": 415,
  "hash_contenido": "ea474dac93e1691406ad2487ab543f42604f2eb24cbd4dd8433d9fab33c958f7",
  "creacion": "2026-03-04",
  "modificacion": "2026-03-05",
  "tags": [
    "re",
    "COMMENT_SYNTAX",
    "hashlib",
    ".config",
    "json"
  ],
  "descripcion_corta": "",
  "descripcion_larga": ""
}
"""
import re
import json
import hashlib
from .config import COMMENT_SYNTAX, DATA_ONLY_EXTENSIONS


def extract_dependencies(content, ext):
    deps = set()
    if ext in ['.js', '.ts', '.jsx', '.tsx']:
        deps.update(re.findall(r'import\s+.*?\s+from\s+[\'"]([^\'"]+)[\'"]', content))
        deps.update(re.findall(r'require\([\'"]([^\'"]+)[\'"]\)', content))
    elif ext == '.py':
        deps.update(re.findall(r'import\s+([a-zA-Z0-9_]+)', content))
        deps.update(re.findall(r'from\s+([a-zA-Z0-9_\.]+)\s+import', content))
    return list(deps)


def split_metadata_and_code(content, ext):
    syntax = COMMENT_SYNTAX.get(ext)
    if not syntax:
        return None, content

    start_tag = syntax['start']
    end_tag = syntax['end']

    if content.startswith(start_tag):
        end_idx = content.find(end_tag)
        if end_idx != -1:
            try:
                raw_json = content[len(start_tag):end_idx].strip()
                metadata = json.loads(raw_json)
                clean_code = content[end_idx + len(end_tag):].lstrip()
                return metadata, clean_code
            except json.JSONDecodeError:
                pass

    return None, content


def inject_metadata(filepath, original_content, clean_code, metadata, ext):
    # Guardia de seguridad: los archivos de datos puros no admiten texto libre.
    # La descripción queda registrada solo en el índice maestro (rag-indexer.json).
    if ext in DATA_ONLY_EXTENSIONS or ext not in COMMENT_SYNTAX:
        return

    syntax = COMMENT_SYNTAX[ext]
    json_formatted = json.dumps(metadata, indent=2, ensure_ascii=False)
    new_content = f"{syntax['start']}{json_formatted}{syntax['end']}{clean_code}"
    if new_content != original_content:
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(new_content)


def calculate_hash(code_string):
    return hashlib.sha256(code_string.encode('utf-8')).hexdigest()
