"""push で送るファイルの選別.

ルートの下のファイルのうち，固定の除外（SPEC_01「安全の枠」の「送信」）と，設定で足した除外
（SPEC_02「`push`」）に当たらないものを送る（SPEC_03「push」）．固定の除外は名前の定数（このモジュール
と `labremote.config` の先頭）と，選別の関数が引数で受け取る場所（読み込んだ設定ファイル・LabRemote
自身のフォルダ）で決まり，設定では減らせない．設定で足せるのは，送らないものだけである．

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

選別の関数は，ファイルの一覧を読むほかは副作用を持たない．LabRemote 自身のフォルダと読み込んだ
設定ファイルの場所は，呼ぶ側（`cli`）が求めて渡す．

「送らない」の判定は `PushRules.is_excluded` の 1 か所にまとめ，フォルダ・ファイルとも次の順で
当てはめる（どれか 1 つに当たれば送らない）．`_walk_files` はこの判定に当たったフォルダに入らず，
当たらなかったものだけをリンクかどうか調べる（除外したフォルダの中のリンクは報告しない）．

1. 固定の除外（`_is_fixed_excluded`）: どの階層でも送らないフォルダ名，ルートの直下で送らない名前，
   結果の置き場（設定の `results.dir`．ルートからの相対パス），場所で決まるもの（設定ファイル・
   LabRemote 自身のフォルダ），`.env`・`.env.*`
2. 設定の除外（`_is_config_excluded`）: `exclude_root`・`exclude_dirs`・`exclude_suffixes`
3. `partial`（`_is_outside_partial_include`）: `path` の直下で `include` に無いもの
4. リンク（`_walk_files`）: 1〜3 に当たらなかったシンボリックリンク・ジャンクション

名前の比べ方は `labremote.config.fold_push_name` だけで決める（`partial` の `include` を除く）．
"""

from __future__ import annotations

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

from labremote.config import (
    DEFAULT_RESULTS_DIR,
    PushConfig,
    find_fixed_excluded_part,
    fold_push_name,
    fold_push_parts,
)

# 固定の除外（SPEC_01「安全の枠」の「送信」）．設定のスキーマに入れず，設定では減らせない．
# 名前は比べる形（`fold_push_name`）で持つ．どの階層でも送らないフォルダ名
# （FIXED_EXCLUDED_DIR_NAMES）とルートの直下で送らない名前（FIXED_EXCLUDED_ROOT_ENTRIES）と，
# 名前がそれに当たるかの判定（`find_fixed_excluded_part`）は，push.partial の path・results.dir の
# 検証でも使うため `labremote.config` に置く
#
# どの階層にあっても送らない環境変数ファイル（`.env` と `.env.*`）．秘密を含みうるため
FIXED_ENV_FILE_NAME = fold_push_name(".env")


@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, ...]


@dataclass(frozen=True)
class PushRules:
    """送らないものの判定に使う規則（固定の除外は定数として常にかかる）.

    名前・パスは比べる形（`fold_push_name`）で持つ（`partial` の `include` だけは書いたまま持ち，
    大文字小文字を区別して比べる．送るものを増やす側に倒さないため）．

    Attributes:
        exclude_root: ルートの直下でだけ送らない名前（設定の `push.exclude_root`）．
        exclude_dirs: どの階層にあっても送らない名前（設定の `push.exclude_dirs`）．
        exclude_suffixes: どの階層にあっても送らないファイルの拡張子（設定の
            `push.exclude_suffixes`）．
        partial: 一部だけ送るフォルダ（比べる形にした `path` の各部分と，`include` の組）．
        excluded_paths: 固定の除外のうち場所で決まるもの（読み込んだ設定ファイル・LabRemote
            自身のフォルダ）の，ルートからの相対パスを比べる形にして分けたもの．
        results_dir: 固定の除外の結果の置き場（設定の `results.dir`）を，比べる形にして
            分けたもの．`output/runs` のように複数の部分を持てるため，ルートからの相対パスで持つ．
    """

    exclude_root: frozenset[str] = frozenset()
    exclude_dirs: frozenset[str] = frozenset()
    exclude_suffixes: tuple[str, ...] = ()
    partial: tuple[tuple[tuple[str, ...], frozenset[str]], ...] = ()
    excluded_paths: frozenset[tuple[str, ...]] = frozenset()
    results_dir: tuple[str, ...] = fold_push_parts(DEFAULT_RESULTS_DIR.split("/"))

    @classmethod
    def from_push(
        cls,
        push: PushConfig | None = None,
        *,
        excluded_paths: Iterable[tuple[str, ...]] = (),
        results_dir: str = DEFAULT_RESULTS_DIR,
    ) -> PushRules:
        """設定の `push` から規則を作る.

        Args:
            push: 設定の `push`．None なら設定の除外は無し（固定の除外だけ）．
            excluded_paths: 固定の除外のうち場所で決まるもの（ルートからの相対パスの各部分）．
            results_dir: 結果の置き場（設定の `results.dir`．ルートからの相対パス）．

        Returns:
            規則．
        """
        push = push or PushConfig()
        return cls(
            exclude_root=frozenset(fold_push_parts(push.exclude_root)),
            exclude_dirs=frozenset(fold_push_parts(push.exclude_dirs)),
            exclude_suffixes=fold_push_parts(push.exclude_suffixes),
            partial=tuple(
                (fold_push_parts(item.parts), frozenset(item.include)) for item in push.partial
            ),
            excluded_paths=frozenset(fold_push_parts(parts) for parts in excluded_paths),
            results_dir=fold_push_parts(results_dir.split("/")),
        )

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

        判定の順序はモジュールの docstring を参照する．名前は `fold_push_parts` で比べる形に
        してから，固定の除外・設定の除外・`partial` の `path` と比べる．

        Args:
            rel_path: POSIX 区切りの相対パス．
            is_dir: フォルダなら True（拡張子・`.env` の除外を当てはめない．中のファイルは
                名前で判断する）．

        Returns:
            除外対象なら True．
        """
        parts = PurePosixPath(rel_path).parts
        if not parts:
            return False
        folded = fold_push_parts(parts)
        return (
            self._is_fixed_excluded(folded, is_dir=is_dir)
            or self._is_config_excluded(folded, is_dir=is_dir)
            or self._is_outside_partial_include(parts, folded, is_dir=is_dir)
        )

    def _is_fixed_excluded(self, folded: tuple[str, ...], *, is_dir: bool) -> bool:
        # 名前で決まる固定の除外（どの階層でも送らないフォルダ名・ルートの直下で送らない名前）．
        # 設定の検証と同じ判定を使う．フォルダ名の除外はファイルにも当てはめる
        # （サブモジュールの `.git` はファイルのため）．`find_fixed_excluded_part` は中で
        # もう一度小文字にするが，結果は変わらない．比べる形を受け取る入口を増やすより，
        # 判定を 1 つに保つ
        if find_fixed_excluded_part(folded) is not None:
            return True
        # 結果の置き場は，サーバ側の結果を上書きしないため，その場所とその中を送らない
        if folded[: len(self.results_dir)] == self.results_dir:
            return True
        # 設定ファイル・LabRemote 自身のフォルダは，その場所とその中を送らない
        if any(folded[: len(path)] == path for path in self.excluded_paths):
            return True
        name = folded[-1]
        return not is_dir and (
            name == FIXED_ENV_FILE_NAME or name.startswith(FIXED_ENV_FILE_NAME + ".")
        )

    def _is_config_excluded(self, folded: tuple[str, ...], *, is_dir: bool) -> bool:
        if folded[0] in self.exclude_root:
            return True
        # exclude_dirs はフォルダの名前だが，同じ名前のファイルも送らない側に倒す
        if any(part in self.exclude_dirs for part in folded):
            return True
        return not is_dir and folded[-1].endswith(self.exclude_suffixes)

    def _is_outside_partial_include(
        self, parts: tuple[str, ...], folded: tuple[str, ...], *, is_dir: bool
    ) -> bool:
        # partial の path の中は include に書いた名前だけを送り，書いていないもの（データ等）を
        # 送らない．include は書いたままの parts と比べる（大文字小文字を区別する）
        for path, include in self.partial:
            depth = len(path)
            if folded[:depth] != path:
                continue
            if len(parts) == depth:
                # partial の path 自体がファイルなら，直下を選べないため送らない
                return not is_dir
            return parts[depth] not in include
        return False


def _relative_parts_under(root: Path, path: Path | None) -> tuple[str, ...] | None:
    """path がルートの下（ルートそのものを除く）にあれば，ルートからの相対パスの各部分を返す."""
    if path is None:
        return None
    try:
        rel = path.resolve().relative_to(root)
    except ValueError:
        return None
    return rel.parts or None


def build_push_rules(
    root: Path,
    push: PushConfig | None = None,
    *,
    config_path: Path | None = None,
    labremote_dir: Path | None = None,
    results_dir: str = DEFAULT_RESULTS_DIR,
) -> PushRules:
    """ルートと設定の `push` から，送らないものの規則を作る.

    Args:
        root: プロジェクトのルート．
        push: 設定の `push`．None なら設定の除外は無し（固定の除外だけ）．
        config_path: 読み込んだ設定ファイル．ルートの下にあれば送らない．
        labremote_dir: LabRemote 自身のフォルダ（実行中の `labremote` パッケージが入っている
            リポジトリ）．ルートの下にあれば，フォルダ全体を送らない．ルートそのもの・ルートの外
            なら何もしない．
        results_dir: 結果の置き場（設定の `results.dir`．ルートからの相対パス）．その場所と
            その中を送らない．

    Returns:
        規則．
    """
    resolved_root = root.resolve()
    excluded = [
        parts
        for parts in (
            _relative_parts_under(resolved_root, config_path),
            _relative_parts_under(resolved_root, labremote_dir),
        )
        if parts is not None
    ]
    return PushRules.from_push(push, excluded_paths=excluded, results_dir=results_dir)


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 is_excluded(rel_path: str, *, is_dir: bool = False, rules: PushRules | None = None) -> bool:
    """ルート基準の相対パスが push から除外されるかを返す.

    Args:
        rel_path: POSIX 区切りの相対パス．
        is_dir: フォルダなら True（拡張子・`.env` の除外を当てはめない）．
        rules: 規則．None なら固定の除外だけ（場所で決まるものを除く）．

    Returns:
        除外対象なら True．
    """
    return (rules or PushRules()).is_excluded(rel_path, is_dir=is_dir)


def _walk_files(root: Path, rules: PushRules, 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 rules.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 rules.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,
    push: PushConfig | None = None,
    *,
    config_path: Path | None = None,
    labremote_dir: Path | None = None,
    results_dir: str = DEFAULT_RESULTS_DIR,
) -> PushSelection:
    """送信するファイルを選び，送らなかったリンクと合わせて返す.

    Args:
        root: プロジェクトのルート．
        push: 設定の `push`．None なら設定の除外は無し（固定の除外だけ）．
        config_path: 読み込んだ設定ファイル（`build_push_rules` を参照）．
        labremote_dir: LabRemote 自身のフォルダ（`build_push_rules` を参照）．
        results_dir: 結果の置き場（設定の `results.dir`．`build_push_rules` を参照）．

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


def collect_push_entries(
    root: Path,
    push: PushConfig | None = None,
    *,
    config_path: Path | None = None,
    labremote_dir: Path | None = None,
    results_dir: str = DEFAULT_RESULTS_DIR,
) -> list[PushEntry]:
    """送信するファイルの一覧を作る（リンクは含まない．`select_push_files` を参照）.

    Args:
        root: プロジェクトのルート．
        push: 設定の `push`．
        config_path: 読み込んだ設定ファイル．
        labremote_dir: LabRemote 自身のフォルダ．
        results_dir: 結果の置き場（設定の `results.dir`）．

    Returns:
        arcname 順に並べた送信対象．
    """
    selection = select_push_files(
        root,
        push,
        config_path=config_path,
        labremote_dir=labremote_dir,
        results_dir=results_dir,
    )
    return list(selection.entries)
