#!/usr/bin/env python3

import os
import sys
import json
import platform
import subprocess
from datetime import datetime
from pathlib import Path

# 添加调试日志到项目的 docs 目录
def log_debug(message):
    try:
        git_root = Path(subprocess.check_output(
            ['git', 'rev-parse', '--show-toplevel'],
            text=True
        ).strip())
        
        docs_dir = git_root / 'docs'
        if docs_dir.exists():
            with open(docs_dir / '.hook_debug.log', 'a') as f:
                f.write(f"{datetime.now()}: {message}\n")
    except:
        pass  # 静默失败，不影响主流程

# 配置日志
def setup_logging():
    """设置日志"""
    try:
        # 获取当前 git 仓库根目录
        git_root = Path(subprocess.check_output(
            ['git', 'rev-parse', '--show-toplevel'],
            text=True
        ).strip())
        
        # 在 git 仓库根目录下创建日志目录
        log_dir = git_root / '.mkdocs_dates'
        log_dir.mkdir(exist_ok=True)
        log_file = log_dir / 'hook.log'
        
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_file),
                logging.StreamHandler(sys.stderr)
            ]
        )
        return True
    except Exception as e:
        print(f"Failed to setup logging: {e}", file=sys.stderr)
        return False

if __name__ == "__main__":
    try:
        log_debug("Hook started")
        update_dates_cache()
        log_debug("Hook completed")
    except Exception as e:
        log_debug(f"Hook error: {e}")
        sys.exit(1)

def find_mkdocs_projects():
    """查找当前 git 仓库中的所有 MkDocs 项目"""
    try:
        git_root = Path(subprocess.check_output(
            ['git', 'rev-parse', '--show-toplevel'],
            text=True
        ).strip())
        
        projects = []
        for config_file in git_root.rglob('mkdocs.y*ml'):
            if config_file.name in ('mkdocs.yml', 'mkdocs.yaml'):
                projects.append(config_file.parent)
        return projects
    except subprocess.CalledProcessError as e:
        print(f"Error finding git root: {e}")
        return []

def get_file_dates(file_path):
    """获取文件的创建和修改时间"""
    try:
        stat = os.stat(file_path)
        modified = datetime.fromtimestamp(stat.st_mtime)

        system = platform.system().lower()
        if system == 'darwin':  # macOS
            try:
                created = datetime.fromtimestamp(stat.st_birthtime)
            except AttributeError:
                created = datetime.fromtimestamp(stat.st_ctime)
        elif system == 'windows':  # Windows
            created = datetime.fromtimestamp(stat.st_ctime)
        else:  # Linux 和其他系统
            created = modified

        return created.isoformat(), modified.isoformat()
    except (OSError, ValueError):
        current_time = datetime.now()
        return current_time.isoformat(), current_time.isoformat()


def update_dates_cache():
    """更新文档时间缓存"""
    for project_dir in find_mkdocs_projects():
        docs_dir = project_dir / 'docs'
        if not docs_dir.exists():
            continue

        logging.info(f"Processing MkDocs project: {project_dir}")
        logging.info(f"Docs directory: {docs_dir}")

        dates_cache = {}
        for md_file in docs_dir.rglob("*.md"):
            rel_path = str(md_file.relative_to(docs_dir))
            created, modified = get_file_dates(md_file)
            dates_cache[rel_path] = {
                "created": created,
                "modified": modified
            }
            logging.info(f"Processing file: {rel_path}")

        cache_file = docs_dir / '.dates_cache.json'
        logging.info(f"Saving cache to: {cache_file}")
        
        try:
            with open(cache_file, "w") as f:
                json.dump(dates_cache, f, indent=2, ensure_ascii=False)
            subprocess.run(["git", "add", str(cache_file)], check=True)
            logging.info(f"Added cache file to git: {cache_file}")
        except Exception as e:
            logging.error(f"Error handling cache file: {e}")
            raise
