"""Filesystem layout for code-review result files.

The two modes deliberately live under different roots: an okstra session
review belongs to its task bundle, while a session-independent branch
review belongs to the authoring tree. Centralising the assembly here keeps
skill markdown from re-deriving literal paths.
"""
from __future__ import annotations

import re
from pathlib import Path

from . import paths

REVIEW_DIRNAME = "code-reviews"
BRANCH_REVIEW_ROOT = ".project-docs"

_STAGE_FILE_RE = re.compile(r"^stage-(\d+)(?:-r(\d+))?\.md$")
_BRANCH_FILE_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})-(\d+)\.md$")


def stage_review_dir(project_root: Path, task_group: str, task_id: str) -> Path:
    """Review directory inside the task bundle."""
    return paths.task_dir(project_root, task_group, task_id) / REVIEW_DIRNAME


def branch_review_dir(project_root: Path, branch: str) -> Path:
    """Review directory for a branch. Slashes stay as nested directories."""
    return Path(project_root) / BRANCH_REVIEW_ROOT / REVIEW_DIRNAME / branch


def _existing_names(review_dir: Path) -> list[str]:
    if not Path(review_dir).is_dir():
        return []
    return [entry.name for entry in Path(review_dir).iterdir() if entry.is_file()]


def next_stage_review(review_dir: Path, stage: int) -> tuple[Path, int]:
    """Next round's file path and round number for one stage.

    Round 1 carries no suffix; later rounds are `-r<N>`.
    """
    highest = 0
    for name in _existing_names(review_dir):
        matched = _STAGE_FILE_RE.match(name)
        if not matched or int(matched.group(1)) != stage:
            continue
        highest = max(highest, int(matched.group(2) or 1))
    round_no = highest + 1
    stem = f"stage-{stage:02d}"
    suffix = "" if round_no == 1 else f"-r{round_no}"
    return Path(review_dir) / f"{stem}{suffix}.md", round_no


def next_branch_review(review_dir: Path, date: str) -> tuple[Path, int]:
    """Next file path and sequence number for a branch review on `date`."""
    highest = 0
    for name in _existing_names(review_dir):
        matched = _BRANCH_FILE_RE.match(name)
        if not matched or matched.group(1) != date:
            continue
        highest = max(highest, int(matched.group(2)))
    seq = highest + 1
    return Path(review_dir) / f"{date}-{seq:02d}.md", seq
