"""
VideoDetection - 100% Relative Path Manager for Portable Zero-Install Architecture.
Tất cả đường dẫn đều được tính toán tương đối từ thư mục gốc của ứng dụng.
"""
from __future__ import annotations

import os
import shutil
import sys
from pathlib import Path


def get_app_root() -> Path:
    """
    Xác định thư mục gốc của ứng dụng độc lập (Portable).
    Hoạt động chuẩn xác khi chạy mã nguồn Python trực tiếp hoặc khi được đóng gói thành exe/portable.
    """
    if getattr(sys, "frozen", False):
        # Ứng dụng chạy từ file đóng gói (PyInstaller / Nuitka / Embedded)
        return Path(sys.executable).resolve().parent
    # Ứng dụng chạy từ mã nguồn: src/core/paths.py -> parents[2] là VideoDetection/
    return Path(__file__).resolve().parents[2]


APP_ROOT: Path = get_app_root()

# Thư mục nghiệp vụ chuẩn hóa
TARGET_DIR: Path = APP_ROOT / "Target"
DATA_DIR: Path = APP_ROOT / "Data"
TEMP_DIR: Path = APP_ROOT / "Temp"
BIN_DIR: Path = APP_ROOT / "bin"
MODELS_DIR: Path = APP_ROOT / "models"
SRC_DIR: Path = APP_ROOT / "src"

# Tự động đảm bảo các thư mục luôn tồn tại
for directory in (TARGET_DIR, DATA_DIR, TEMP_DIR, BIN_DIR, MODELS_DIR):
    directory.mkdir(parents=True, exist_ok=True)


def get_ffmpeg_path() -> str:
    """
    Ưu tiên tuyệt đối binary portable trong bin/ffmpeg.exe.
    Nếu không thấy thì fallback sang hệ thống.
    """
    local_ffmpeg = BIN_DIR / "ffmpeg.exe" if os.name == "nt" else BIN_DIR / "ffmpeg"
    if local_ffmpeg.exists():
        return str(local_ffmpeg)
    system_ffmpeg = shutil.which("ffmpeg")
    if system_ffmpeg:
        return system_ffmpeg
    return str(local_ffmpeg)


def get_ffprobe_path() -> str:
    """
    Ưu tiên binary portable trong bin/ffprobe.exe.
    """
    local_ffprobe = BIN_DIR / "ffprobe.exe" if os.name == "nt" else BIN_DIR / "ffprobe"
    if local_ffprobe.exists():
        return str(local_ffprobe)
    system_ffprobe = shutil.which("ffprobe")
    if system_ffprobe:
        return system_ffprobe
    return str(local_ffprobe)


def clean_temp_dir(keep_gitkeep: bool = True) -> int:
    """
    Dọn dẹp sạch sẽ các file tạm trong thư mục Temp/.
    Trả về số lượng file/thư mục đã dọn dẹp.
    """
    removed_count = 0
    if not TEMP_DIR.exists():
        return 0

    for item in TEMP_DIR.iterdir():
        if keep_gitkeep and item.name == ".gitkeep":
            continue
        try:
            if item.is_file() or item.is_symlink():
                item.unlink(missing_ok=True)
                removed_count += 1
            elif item.is_dir():
                shutil.rmtree(item, ignore_errors=True)
                removed_count += 1
        except Exception:
            pass
    return removed_count
