from aiservice.common.markdown_utils import split_markdown_code

__all__ = ["group_code", "is_markdown_structure_changed", "is_multi_context", "split_markdown_code"]


def is_multi_context(code: str) -> bool:
    """Check if code is in multi-file markdown format (Python)."""
    return code.strip().startswith("```python:")


def is_multi_context_js(code: str) -> bool:
    """Check if code is in multi-file markdown format (JavaScript)."""
    stripped = code.strip()
    return stripped.startswith("```javascript:") or stripped.startswith("```js:")


def is_multi_context_ts(code: str) -> bool:
    """Check if code is in multi-file markdown format (TypeScript)."""
    stripped = code.strip()
    return stripped.startswith("```typescript:") or stripped.startswith("```ts:")


def is_multi_context_any(code: str) -> bool:
    """Check if code is in multi-file markdown format for any supported language."""
    return is_multi_context(code) or is_multi_context_js(code) or is_multi_context_ts(code)


def is_markdown_structure_changed(old: str, new: str, language: str = "python") -> bool:
    old_files = split_markdown_code(old, language).keys()
    new_files = split_markdown_code(new, language).keys()
    return old_files != new_files


def group_code(file_to_code: dict[str, str], language: str = "python") -> str:
    def format_block(file_path: str, code: str) -> str:
        # Ensure the code ends with a newline before the closing ```
        normalized = code if code.endswith("\n") else code + "\n"
        return f"```{language}:{file_path}\n{normalized}```"

    return "\n".join(format_block(path, code) for path, code in file_to_code.items())
