import json
import re
import os
from datetime import datetime

MAX_CONTENT_LENGTH = 50000
MAX_TAGS_COUNT = 20
MAX_TAG_LENGTH = 50
MAX_TITLE_LENGTH = 200


def now_iso() -> str:
    """返回当前时间的 ISO 格式字符串（带时区）"""
    return datetime.now().astimezone().isoformat()


def validate_content(content: str) -> str:
    if not content or not isinstance(content, str):
        raise ValueError("content is required and must be a string")
    if len(content) > MAX_CONTENT_LENGTH:
        raise ValueError(f"content exceeds {MAX_CONTENT_LENGTH} chars")
    return content


def normalize_tags(tags) -> list[str] | None:
    """将各种格式的 tags 统一为 list[str]，None 保持 None"""
    if tags is None:
        return None
    if isinstance(tags, str):
        try:
            tags = json.loads(tags)
        except (json.JSONDecodeError, TypeError):
            tags = [t.strip() for t in tags.split(",") if t.strip()]
    return tags if isinstance(tags, list) else [tags]


def validate_tags(tags) -> list[str]:
    tags = normalize_tags(tags) or []
    if not isinstance(tags, list):
        raise ValueError("tags must be a list")
    if len(tags) > MAX_TAGS_COUNT:
        raise ValueError(f"tags exceeds {MAX_TAGS_COUNT} items")
    for t in tags:
        if not isinstance(t, str):
            raise ValueError(f"each tag must be a string, got: {type(t).__name__}")
        if len(t) > MAX_TAG_LENGTH:
            raise ValueError(f"tag '{t[:20]}...' exceeds {MAX_TAG_LENGTH} chars")
    return tags


_TABLE_WHITELIST = {"memories", "user_memories", "vec_memories", "vec_user_memories",
                    "memory_tags", "user_memory_tags"}


def safe_table(name: str) -> str:
    if name not in _TABLE_WHITELIST:
        raise ValueError(f"Invalid table: {name}")
    return name


def contains_project_path(content: str) -> bool:
    """检测 content 是否包含用户目录下的项目路径（非系统路径）。
    用于防止项目特定信息被存为全局记忆，避免跨项目操作。"""
    home = os.path.expanduser("~")
    # 匹配用户目录下的路径：/Users/xxx/、/home/xxx/、C:\Users\xxx\
    patterns = [
        re.escape(home) + r'/\S+',           # 当前用户 home 下的路径
        r'/Users/\w+/\S+',                    # macOS 其他用户
        r'/home/\w+/\S+',                     # Linux
        r'[A-Z]:\\Users\\\w+\\\S+',           # Windows
        r'~/\S+',                             # ~ 开头的路径
    ]
    # 系统路径白名单前缀（不算项目路径）
    system_prefixes = (
        '/usr/', '/etc/', '/bin/', '/sbin/', '/opt/homebrew/',
        '/var/', '/tmp/', '/Library/', '/System/',
        home + '/.', home + '/Library',       # dotfiles 和 macOS Library
    )
    for pat in patterns:
        for m in re.finditer(pat, content):
            path = m.group(0).rstrip('.,;:)]\'"')
            if not any(path.startswith(sp) for sp in system_prefixes):
                return True
    return False


def validate_title(title: str) -> str:
    if not title or not isinstance(title, str):
        raise ValueError("title is required and must be a string")
    if len(title) > MAX_TITLE_LENGTH:
        raise ValueError(f"title exceeds {MAX_TITLE_LENGTH} chars")
    return title
