import time
from fastapi.templating import Jinja2Templates
from devplacepy.config import TEMPLATES_DIR
from devplacepy.constants import TOPICS
from devplacepy.database import get_table
from devplacepy.avatar import avatar_url
from devplacepy.utils import format_date as _format_date
from devplacepy.seo import (
    site_url, combine,
    website_schema, breadcrumb_schema,
    discussion_forum_posting, profile_page_schema,
    software_application_schema, truncate,
)
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))

_unread_cache = {}
_UNREAD_CACHE_TTL = 60

def clear_unread_cache(user_uid: str) -> None:
    _unread_cache.pop(user_uid, None)


def jinja_unread_count(user_uid: str) -> int:
    cached = _unread_cache.get(user_uid)
    if cached:
        entry, expiry = cached
        if time.time() < expiry:
            return entry
        _unread_cache.pop(user_uid, None)
    notifs = get_table("notifications")
    count = len(list(notifs.find(user_uid=user_uid, read=False)))
    _unread_cache[user_uid] = (count, time.time() + _UNREAD_CACHE_TTL)
    return count

def jinja_user_projects(user_uid: str) -> list:
    projects = get_table("projects")
    return list(projects.find(user_uid=user_uid))

templates.env.globals["get_unread_count"] = jinja_unread_count
templates.env.globals["get_user_projects"] = jinja_user_projects
templates.env.globals["avatar_url"] = avatar_url
templates.env.globals["format_date"] = _format_date
templates.env.globals["TOPICS"] = TOPICS
def jinja_max_upload_size_mb():
    from devplacepy.database import get_setting
    return int(get_setting("max_upload_size_mb", "10"))

def jinja_max_attachments():
    from devplacepy.database import get_setting
    return int(get_setting("max_attachments_per_resource", "10"))

def jinja_allowed_file_types():
    from devplacepy.database import get_setting
    return get_setting("allowed_file_types", "")

templates.env.globals["max_upload_size_mb"] = jinja_max_upload_size_mb
templates.env.globals["max_attachments_per_resource"] = jinja_max_attachments
templates.env.globals["allowed_file_types"] = jinja_allowed_file_types

_LANGUAGE_NAMES = {
    "python": "Python", "javascript": "JavaScript", "typescript": "TypeScript",
    "html": "HTML", "css": "CSS", "c": "C", "cpp": "C++", "java": "Java",
    "go": "Go", "rust": "Rust", "sql": "SQL", "bash": "Bash",
    "yaml": "YAML", "json": "JSON", "markdown": "Markdown",
    "swift": "Swift", "php": "PHP", "ruby": "Ruby", "kotlin": "Kotlin",
    "lua": "Lua", "perl": "Perl", "haskell": "Haskell", "elixir": "Elixir",
    "r": "R", "dart": "Dart", "scala": "Scala", "plaintext": "Plain Text",
}

def jinja_language_name(code: str) -> str:
    return _LANGUAGE_NAMES.get(code, code)

templates.env.globals["language_name"] = jinja_language_name

from devplacepy.attachments import format_file_size, file_icon_emoji
templates.env.globals["format_file_size"] = format_file_size
templates.env.globals["file_icon_emoji"] = file_icon_emoji
