import os
import sys
from moviepy.editor import VideoFileClip

def format_filesize(size):
# ファイルサイズを3桁毎にカンマを入れてフォーマット
return f"{size:,.0f}"

def format_duration(duration, use_hms=False):
if use_hms:
hours, remainder = divmod(duration, 3600)
minutes, seconds = divmod(remainder, 60)
# 時間、分、秒が1桁の場合も空白を含めて2桁で表示
return f"{int(hours):02d}時間 {int(minutes):02d}{int(seconds):02d}秒"
else:
return f"{int(duration)}秒"

def calculate_total_duration(directory_path, use_hms=False):
# ディレクトリ内の動画ファイルの一覧を取得
video_files = [f for f in os.listdir(directory_path) if f.endswith(('.mp4', '.avi', '.mkv'))]

total_duration = 0 # 合計再生時間(秒)

# HTML出力の開始部分
if use_hms:
html_output = "<html><body><h1>動画ファイル一覧</h1><table><tr><th width='160'>再生時間</th><th width='160'>ファイルサイズ</th><th>ファイル名</th></tr>"
else:
html_output = "<html><body><h1>動画ファイル一覧</h1><table><tr><th width='130'>再生時間</th><th width='160'>ファイルサイズ</th><th>ファイル名</th></tr>"

# 各動画ファイルの再生時間とファイルサイズを計算し、HTMLに追加
for video_file in video_files:
video_path = os.path.join(directory_path, video_file)
try:
video_clip = VideoFileClip(video_path)
duration = video_clip.duration
size = os.path.getsize(video_path) # ファイルサイズ(バイト)

# ファイル名が長すぎる場合にはセル内で改行
if len(video_file) > 70:
video_file = "<br>".join([video_file[i:i+70] for i in range(0, len(video_file), 70)])

# 個別の再生時間、ファイルサイズをフォーマットしてHTMLの表に追加
formatted_duration = format_duration(duration, use_hms)
formatted_size = format_filesize(size)
if use_hms:
html_output += f"<tr><td style='text-align:right;' width='160'>{formatted_duration}</td><td style='text-align:right;' width='160'>{formatted_size}バイト</td><td>{video_file}</td></tr>"
else:
html_output += f"<tr><td style='text-align:right;' width='130'>{formatted_duration}</td><td style='text-align:right;' width='160'>{formatted_size}バイト</td><td>{video_file}</td></tr>"

total_duration += duration
video_clip.close() # 明示的にクローズ
except Exception as e:
print(f"エラー: {video_file} を処理中にエラーが発生しました。")
print(e)

# 合計再生時間を時間単位に変換
total_hours = int(total_duration) // 3600
total_minutes = (int(total_duration) % 3600) // 60
total_seconds = int(total_duration) % 60

# 合計再生時間をHTMLに追加
html_output += f"</table><h2>合計再生時間: {total_hours:02d} 時間, {total_minutes:02d} 分, {total_seconds:02d} 秒</h2></body></html>"

# 出力ファイル名を生成
base_directory_name = os.path.basename(directory_path)
output_filename = f"video_info_{base_directory_name}.html"

# 結果を生成された出力ファイルに保存
with open(output_filename, "w") as html_file:
html_file.write(html_output)

if __name__ == "__main__":
# コマンドライン引数からディレクトリパスを取得
if len(sys.argv) >= 2:
directory_path = sys.argv[1]
use_hms = "-hms" in sys.argv # -hms オプションが指定されたら True にする
else:
print("使用法: python script.py ディレクトリパス [-hms]")
sys.exit(1)

calculate_total_duration(directory_path, use_hms)