"""push で送るファイルの選別と，手元のプロジェクトルートの探索.

リポジトリ内のコード一式を送り，キャッシュ・仮想環境・データ・実験結果・原本・重み・
Claude の設定は送らない（SPEC_03「移植で変える点」）．サブモジュール TIASDataHub は
サーバの `uv sync` が tiasdata を導入するのに要るものだけを送る．

シンボリックリンクとジャンクション（Windows の reparse point）は，ファイル・ディレクトリとも
送らず，リンクのディレクトリの中にも入らない（リンク先がリポジトリの外・`legacy/`・`data/` でも
名前だけでは分からないため．学習データ・原本をサーバへ送る経路を作らない）．

TIASJudgeModel の `tias_judge_model.remote.files` の移植．`legacy/`・重みの拡張子・`.env`・
リンクの除外を足した（移植元はリンク先の中身を送っていた）．
"""

from __future__ import annotations

import os
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path, PurePosixPath

# どの階層にあっても送らないディレクトリ名（.venv は Windows 用でサーバでは使えない）
EXCLUDED_DIR_NAMES = frozenset({".git", ".venv", "__pycache__", ".pytest_cache", ".ruff_cache"})
# プロジェクト直下でだけ除外するエントリ．data/ は学習データ・合成データの置き場，runs/ は
# サーバ側の実験結果を上書きしないため，.claude/ は手元の Claude Code 設定のため送らない．
# legacy/ は原本で，約 4 GB の重みと画像のファイル名を含む結果があるため送らない（SPEC_03）．
# 直下に限るのは src/tongue_seg_model/data/（パッケージ）・tests/data/ を送るため
EXCLUDED_ROOT_ENTRIES = frozenset({"data", "runs", ".claude", "legacy"})
# どの階層にあっても送らない拡張子（小文字で比べる）．重みは data/・runs/・legacy/ の外に
# 置かれていても送らない（.gitignore の重みの拡張子と同じ）
EXCLUDED_SUFFIXES = frozenset({".pt", ".pth", ".ckpt", ".pb", ".onnx"})
# どの階層にあっても送らないファイル名（環境変数ファイル．秘密を含みうる．.gitignore と同じ）
_ENV_FILE_NAME = ".env"

# サブモジュールのうち，サーバで `uv` が tiasdata を導入するのに要るものだけを送る
# （README.md は uv_build が要求する）．.claude/・docs/・tests/・datasets/ 等は送らない
# （実行に要らず，手元の設定や別リポジトリの文書をサーバに広げないため）．
_SUBMODULE_PARTS = ("external", "TIASDataHub")
_SUBMODULE_SENT_ENTRIES = frozenset({"pyproject.toml", "README.md", "src"})

_PACKAGE_DIR = Path("src") / "labremote"


@dataclass(frozen=True)
class PushEntry:
    """送信するファイル 1 件.

    Attributes:
        path: 手元の実ファイル．
        arcname: リモートのプロジェクトルート基準の相対パス（POSIX 区切り）．
        size: バイト数．
    """

    path: Path
    arcname: str
    size: int


@dataclass(frozen=True)
class PushSelection:
    """送信対象の選別結果.

    Attributes:
        entries: 送信するファイル（arcname 順）．
        skipped_links: 送らなかったリンク（シンボリックリンク・ジャンクション）の
            プロジェクトルート基準の相対パス（POSIX 区切り，順に並べたもの）．除外対象の
            ディレクトリ（`.venv/` 等）の中のリンクは含まない．
    """

    entries: tuple[PushEntry, ...]
    skipped_links: tuple[str, ...]


def is_link(path: Path) -> bool:
    """path がシンボリックリンクかジャンクション（Windows の reparse point）かを返す.

    `Path.is_symlink()` はジャンクションを見分けないため `os.path.isjunction` も見る．
    リンク先が無い（壊れた）リンクも True．

    Args:
        path: 調べるパス．

    Returns:
        リンクなら True．
    """
    return path.is_symlink() or os.path.isjunction(path)


def find_project_root(start: Path) -> Path:
    """start から上方向にたどり，このリポジトリのルートを探す.

    Args:
        start: 探索を始めるディレクトリ（通常はカレントディレクトリ）．

    Returns:
        `pyproject.toml` と `src/labremote/` を持つディレクトリ．

    Raises:
        ValueError: 見つからない場合．
    """
    start = start.resolve()
    for directory in (start, *start.parents):
        if (directory / "pyproject.toml").is_file() and (directory / _PACKAGE_DIR).is_dir():
            return directory
    raise ValueError(
        f"{start} から上にプロジェクトルート（pyproject.toml と src/labremote/）が"
        "見つからない．リポジトリ内で実行する"
    )


def _is_excluded_file_name(name: str) -> bool:
    """ファイル名だけで除外が決まるもの（重みの拡張子・環境変数ファイル）か."""
    lowered = name.lower()
    if lowered == _ENV_FILE_NAME or lowered.startswith(_ENV_FILE_NAME + "."):
        return True
    return PurePosixPath(lowered).suffix in EXCLUDED_SUFFIXES


def is_excluded(rel_path: str, *, is_dir: bool = False) -> bool:
    """プロジェクトルート基準の相対パスが push から除外されるかを返す.

    Args:
        rel_path: POSIX 区切りの相対パス．
        is_dir: ディレクトリなら True（拡張子・ファイル名による除外を当てはめない）．

    Returns:
        除外対象なら True．
    """
    parts = PurePosixPath(rel_path).parts
    if not parts:
        return False
    # 大文字小文字を区別せずに比べる（手元の Windows では `Legacy/` も `legacy/` と同じ場所のため）
    lowered = [part.lower() for part in parts]
    if lowered[0] in EXCLUDED_ROOT_ENTRIES or any(part in EXCLUDED_DIR_NAMES for part in lowered):
        return True
    if not is_dir and _is_excluded_file_name(parts[-1]):
        return True
    depth = len(_SUBMODULE_PARTS)
    return (
        len(parts) > depth
        and parts[:depth] == _SUBMODULE_PARTS
        and parts[depth] not in _SUBMODULE_SENT_ENTRIES
    )


def _walk_files(root: Path, skipped_links: list[str]) -> Iterator[PushEntry]:
    """root 配下のファイルを，除外規則を適用しつつ決定的な順で列挙する.

    リンク（ファイル・ディレクトリとも）は送らず，その相対パスを skipped_links に足す．
    os.walk は既定でシンボリックリンクのディレクトリに入らないが，ジャンクションには入りうる
    ため，dirnames から明示的に除いて入らないようにする．
    """
    for dirpath, dirnames, filenames in os.walk(root):
        dir_rel = Path(dirpath).relative_to(root).as_posix()
        prefix = "" if dir_rel == "." else f"{dir_rel}/"
        kept: list[str] = []
        for dirname in sorted(dirnames):
            rel = prefix + dirname
            if is_excluded(rel, is_dir=True):
                continue
            if is_link(Path(dirpath) / dirname):
                skipped_links.append(rel)
                continue
            kept.append(dirname)
        dirnames[:] = kept
        for filename in sorted(filenames):
            rel = prefix + filename
            path = Path(dirpath) / filename
            if is_excluded(rel):
                continue
            if is_link(path):
                skipped_links.append(rel)
                continue
            if not path.is_file():
                continue
            yield PushEntry(path=path, arcname=rel, size=path.stat().st_size)


def select_push_files(root: Path) -> PushSelection:
    """送信するファイルを選び，送らなかったリンクと合わせて返す.

    Args:
        root: プロジェクトルート．

    Returns:
        arcname 順に並べた送信対象と，送らなかったリンク．
    """
    skipped_links: list[str] = []
    entries = sorted(_walk_files(root.resolve(), skipped_links), key=lambda entry: entry.arcname)
    return PushSelection(tuple(entries), tuple(sorted(skipped_links)))


def collect_push_entries(root: Path) -> list[PushEntry]:
    """送信するファイルの一覧を作る（リンクは含まない．`select_push_files` を参照）.

    Args:
        root: プロジェクトルート．

    Returns:
        arcname 順に並べた送信対象．
    """
    return list(select_push_files(root).entries)
