"""Rust 正则分块（Phase 1 简版，Phase 2 替换为 tree-sitter）"""

from __future__ import annotations

import re

from .base import BaseChunker, Chunk
from .text import TextChunker

# Rust 顶层定义的正则模式
_RUST_PATTERNS = [
    re.compile(r"^(?:pub\s+)?(?:async\s+)?fn\s+\w+", re.MULTILINE),
    re.compile(r"^(?:pub\s+)?struct\s+\w+", re.MULTILINE),
    re.compile(r"^(?:pub\s+)?enum\s+\w+", re.MULTILINE),
    re.compile(r"^impl\s+", re.MULTILINE),
    re.compile(r"^(?:pub\s+)?mod\s+\w+", re.MULTILINE),
    re.compile(r"^(?:pub\s+)?trait\s+\w+", re.MULTILINE),
]


class RustChunker(BaseChunker):
    """按 fn/struct/impl 等关键字分割 Rust 文件"""

    def chunk(self, content: str, file_path: str) -> list[Chunk]:
        splits = _find_split_points(content)
        if len(splits) < 2:
            return TextChunker().chunk(content, file_path)
        return _build_chunks(content, splits)


class JavaScriptChunker(BaseChunker):
    """按 function/class 分割 JS/TS 文件"""

    def chunk(self, content: str, file_path: str) -> list[Chunk]:
        splits = _find_split_points_js(content)
        if len(splits) < 2:
            return TextChunker().chunk(content, file_path)
        return _build_chunks(content, splits)


# ── JS/TS 模式 ──

_JS_PATTERNS = [
    re.compile(r"^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+\w+", re.MULTILINE),
    re.compile(r"^(?:export\s+)?(?:default\s+)?class\s+\w+", re.MULTILINE),
    re.compile(r"^(?:export\s+)?const\s+\w+\s*=\s*(?:async\s+)?\(", re.MULTILINE),
]


def _find_split_points(content: str) -> list[int]:
    """找到 Rust 代码的分割点（行偏移）"""
    points = set()
    for pattern in _RUST_PATTERNS:
        for match in pattern.finditer(content):
            points.add(match.start())
    return sorted(points)


def _find_split_points_js(content: str) -> list[int]:
    """找到 JS/TS 代码的分割点"""
    points = set()
    for pattern in _JS_PATTERNS:
        for match in pattern.finditer(content):
            points.add(match.start())
    return sorted(points)


def _build_chunks(content: str, splits: list[int]) -> list[Chunk]:
    """根据分割点构造 Chunk 列表"""
    chunks: list[Chunk] = []

    # header（分割点前的内容）
    if splits[0] > 0:
        header = content[:splits[0]].strip()
        if header:
            chunks.append(Chunk(content=header, section="header", chunk_index=0))

    for i, start in enumerate(splits):
        end = splits[i + 1] if i + 1 < len(splits) else len(content)
        text = content[start:end].strip()
        if not text:
            continue

        # 从第一行提取 section 名
        first_line = text.split("\n", 1)[0].strip()
        section = first_line[:80]  # 截断过长的行

        chunks.append(Chunk(
            content=text,
            section=section,
            chunk_index=len(chunks),
        ))

    return chunks
