from __future__ import annotations

import html
import re
from typing import Literal


ResolvedLang = Literal["en", "tc"]


# 协议原文（直接来自仓库中的 Markdown 文档）。
# 说明：为了保证“点击一定有内容”，这里在后端内置了一份可展示的协议文本。
# 线上若你们有官网/静态站点托管页面，可通过环境变量 LEGAL_* 覆盖为外部链接。
PRIVACY_POLICY_MD = """Hey Mama | Privacy Policy
Last updated: February 2026

1. Introduction
Welcome to Hey Mama (“the App,” “we,” “us”).
We respect your privacy and are committed to protecting your personal information. This Privacy Policy explains how we collect, use, store, and protect information when you use the App.
By downloading, accessing, or using the App, you acknowledge that you have read, understood, and agreed to this Privacy Policy.

2. Data Controller and Scope
The App is operated and maintained by the Hey Mama team.
This Privacy Policy applies to information processing activities related to your use of the App.

3. Information We Collect
3.1 Information You Provide
Hey Mama does not require account registration and does not require you to provide personally identifiable information.
During your use of the App, you may optionally provide or generate the following information:
- Reminder settings (e.g., reminder frequency)
- Text content you view, save as favorites, or create within the App (if available)
This information is used only to operate core App features and provide a personalized experience.

3.2 Information Collected Automatically
When you use the App, we may automatically collect certain non-identifiable technical information, including but not limited to:
- Device type and operating system version
- App version
- Device language settings
- Basic usage status (e.g., whether the App is opened, whether reminders are enabled)
This information does not directly identify you and is primarily used to maintain App stability, troubleshoot issues, and improve user experience.
The App does not collect precise location information for the purposes described in this policy, does not engage in cross-app tracking, and does not use your data for third-party advertising.

4. Push Notifications
With your permission, the App may send you reminder notifications, such as daily affirmations.
- Notifications contain general text information only
- Notifications do not include sensitive personal data
- You can disable notifications at any time in your device settings

5. Home Screen Widgets
If you choose to use home screen widgets, the displayed content comes from the App’s text-based affirmations. Widgets do not collect or transmit additional personal data.

6. How We Use Information
We use collected information only for the following purposes:
- To provide and maintain core App functionality
- To improve content presentation and user experience
- To fix bugs and enhance system stability
We do not:
- Sell, rent, or trade your personal data
- Use your data for third-party advertising purposes

7. Third-Party Services
Hey Mama currently does not integrate third-party advertising or marketing services.
The App may rely on necessary operating system and app store services to provide functionality (for example, push notification delivery mechanisms).
If we later integrate third-party analytics or technical services, we will update this Privacy Policy accordingly.

8. Data Retention and Security
We retain information only for as long as necessary to achieve the purposes described above. We implement reasonable technical and organizational measures to protect information against unauthorized access, disclosure, alteration, or loss.

9. Minors
Hey Mama is not designed for children, and we do not knowingly collect personal information from users under the age of 13.
If you are a minor, please use the App with the consent and supervision of a parent or guardian.

10. Changes to This Privacy Policy
We may update this Privacy Policy from time to time. The updated version will be made available within the App or through related pages. If you continue to use the App after updates take effect, you are deemed to have accepted the updated policy.


---
Hey Mama｜隱私權政策
最後更新日期：2026 年 2 月

一、前言
歡迎使用 Hey Mama（以下簡稱「本 App」、「我們」）。
我們重視您的隱私，並致力於保護您的個人資料安全。本隱私權政策說明您在使用 Hey Mama 時，我們如何收集、使用、保存與保護相關資訊。
當您下載、存取或使用本 App，即表示您已閱讀、理解並同意本隱私權政策之內容。

二、我們收集的資訊
1. 使用者主動提供的資訊
Hey Mama 不要求建立帳號，亦不強制使用者提供可識別個人身分的資料。
在使用過程中，您可能會選擇性提供或產生以下資訊：
- 提醒設定（例如提醒頻率）
- 使用者在 App 內閱讀、收藏或建立的文字內容（如有）
上述資訊僅用於 App 功能運作與個人化體驗。
2. 自動收集的資訊
當您使用本 App 時，我們可能會自動收集部分非識別性技術資訊，包括但不限於：
- 裝置類型與作業系統版本
- App 版本
- 裝置語言設定
- 基本使用行為（例如是否開啟 App、是否啟用提醒）
這些資訊無法直接識別您的身分，僅用於維持 App 穩定性與改善使用體驗。

三、推送通知
在取得您同意後，Hey Mama 可能會向您發送提醒推送，例如每日肯定語提示。
- 推送內容僅包含一般文字資訊
- 不包含任何敏感個人資料
- 您可隨時於裝置系統設定中關閉通知功能

四、桌面小組件
若您選擇使用桌面小組件，其顯示內容僅來自 App 內的文字肯定語，不會額外收集或傳送新的個人資料。

五、資訊使用方式
我們僅於下列目的範圍內使用所收集的資訊：
- 提供與維護 App 的基本功能
- 改善內容呈現與使用體驗
- 修復錯誤與提升系統穩定性
我們不會：
- 出售、出租或交換您的個人資料
- 將資料用於第三方廣告投放

六、第三方服務
目前 Hey Mama 未整合第三方廣告或行銷服務。
 如未來整合第三方分析或技術服務，我們將於本政策中另行說明並更新。

七、資料保存與安全
我們僅在達成上述目的所需期間內保存相關資訊，並採取合理的技術與管理措施，以防止資料遭未經授權存取、洩漏、竄改或遺失。

八、未成年人說明
Hey Mama 並非專為兒童設計，亦不刻意收集未滿 13 歲使用者的個人資料。
若您為未成年人，請在監護人同意與陪同下使用本 App。

九、隱私權政策的變更
我們可能會不定期更新本隱私權政策。
更新後的版本將公布於 App 內或相關頁面，您於政策更新後繼續使用本 App，即視為同意更新內容。
"""

TERMS_OF_USE_MD = """Hey Mama – Terms of Use
Last updated: February 2026
Welcome to Hey Mama (“the App,” “we,” or “us”).
Please read these Terms of Use carefully before downloading, accessing, or using the App. By using the App, you agree to be bound by these Terms.

1. Intended Audience
Hey Mama is intended for adults only.
The App is not designed for children, and users must ensure they have the legal capacity to use the App under applicable laws.

2. Services Provided
Hey Mama provides text-based content and features, including but not limited to:
- Daily affirmations and mindfulness text
- User-configured reminders and push notifications
- Home screen widgets displaying affirmation text
- Personalized reading or saving experiences (where applicable)
All content is provided for general emotional support and self-reflection purposes only and does not constitute medical, psychological, or professional advice.

3. Acceptable Use
You agree to:
- Use the App for personal, non-commercial purposes only
- Not copy, reproduce, distribute, sell, modify, reverse engineer, or attempt to extract the source code of the App
- Not engage in any activity that may interfere with the App’s functionality, stability, or user experience
We reserve the right to restrict or terminate access if these Terms are violated.

4. Push Notifications
The App may send push notifications based on your settings (e.g. daily affirmation reminders).
- Notifications contain general text only
- No sensitive personal data is included
- You may disable notifications at any time through your device settings

5. Intellectual Property
All content, design elements, interfaces, and materials within the App are owned by us or our licensors and are protected by applicable intellectual property laws.
Unauthorized use, reproduction, or distribution is strictly prohibited.

6. Disclaimer
The App and its content are provided for informational and self-support purposes only.
- We do not guarantee specific emotional or psychological outcomes
- The App does not replace professional medical, mental health, or legal advice
- You are solely responsible for how you use the content

7. Service Availability
We may modify, suspend, or discontinue any part of the App at any time due to maintenance, updates, or circumstances beyond our control.
We are not liable for any loss or damage resulting from such interruptions or changes.

8. Changes to These Terms
We may update these Terms of Use from time to time.
Updated versions will be made available within the App or related pages. Continued use of the App after changes indicates acceptance of the revised Terms.

9. Governing Law
These Terms shall be governed by and construed in accordance with the applicable laws of our operating jurisdiction.

---
Hey Mama 使用條款
最後更新日期：2026 年 2 月
歡迎使用 Hey Mama（以下簡稱「本 App」、「我們」）。
在下載、存取或使用本 App 前，請您仔細閱讀本使用條款。當您開始使用本 App，即表示您已閱讀、理解並同意遵守本條款。

1. 服務對象與使用資格
Hey Mama 僅供成年人使用（intended for adults）。
 本 App 並非為兒童設計，使用者應確認自己具備依所在地法律使用本服務的完全行為能力。

2. 服務內容
Hey Mama 提供以文字形式為主的內容與功能，包括但不限於：
- 每日肯定語與正念文字內容
- 使用者設定的提醒與推送通知
- 桌面小組件顯示肯定語文字
- 內容閱讀與收藏等個人化體驗（如適用）
本 App 所提供之內容僅作為日常情緒支持與自我提醒用途，不構成任何形式的醫療、心理諮商或專業建議。

3. 使用方式與限制
使用者同意：
- 僅將本 App 用於個人、非商業用途
- 不以任何方式複製、重製、散布、出售、反編譯或試圖取得本 App 之原始碼
- 不進行任何可能影響 App 正常運作、穩定性或其他使用者體驗之行為
如有違反，我們有權在不另行通知的情況下限制或終止使用權限。

4. 推送通知
本 App 可能依使用者設定發送推送通知（例如每日肯定語提醒）。
- 推送內容僅為一般文字資訊
- 不包含個人化敏感資料
- 您可隨時透過裝置系統設定關閉通知功能

5. 智慧財產權
本 App 及其所有內容（包含但不限於文字、設計、介面、版面配置與視覺元素）之智慧財產權，均屬於我們或合法授權方所有。
未經事前書面同意，任何形式之使用、修改、重製或散布皆屬禁止。

6. 免責聲明
本 App 所提供之內容僅供一般參考與自我提醒之用。
- 我們不保證內容能產生特定心理、情緒或行為結果
- 本 App 不取代任何專業醫療、心理或法律建議
- 使用者應自行判斷內容是否適合自身狀況

7. 服務中斷與變更
我們可能因系統維護、功能調整、更新或其他不可抗力因素，暫時中斷或變更本 App 之全部或部分功能。
對於因此可能造成的任何直接或間接損失，我們不負任何責任。

8. 條款修改
我們可能不定期更新本使用條款。
 更新後的版本將公布於 App 內或相關頁面，您於條款更新後繼續使用本 App，即視為同意更新內容。

9. 準據法與管轄
本使用條款之解釋與適用，悉依我們所在地之相關法律規定處理。
"""


def split_bilingual_markdown(text: str) -> tuple[str, str | None]:
    """
    按文档中的 `---` 分隔符将内容拆成两段。

    返回：
    - 第一段：默认视为英文
    - 第二段：默认视为繁体（可为空）
    """

    parts = re.split(r"^\s*---\s*$", text, maxsplit=1, flags=re.MULTILINE)
    if not parts:
        return "", None
    if len(parts) == 1:
        return parts[0].strip(), None
    return parts[0].strip(), parts[1].strip()


def choose_content_by_lang(text: str, lang: ResolvedLang) -> tuple[str, ResolvedLang]:
    """
    根据 lang 选择展示内容。若 tc 内容缺失则回退 en。
    """

    en, tc = split_bilingual_markdown(text)
    if lang == "tc" and tc:
        return tc, "tc"
    return en, "en"


def render_as_simple_html(title: str, content: str) -> str:
    """
    将文本以简单 HTML 的方式展示（使用 pre 保留换行并自动换行）。
    不做 Markdown 渲染，避免引入额外依赖，确保“最小可用、必有内容”。
    """

    safe_title = html.escape(title)
    safe_content = html.escape(content)
    return f"""<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{safe_title}</title>
    <style>
      :root {{
        color-scheme: light dark;
      }}
      body {{
        margin: 0;
        padding: 16px;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, "PingFang TC", "PingFang SC", "Noto Sans CJK TC", "Noto Sans CJK SC", sans-serif;
        line-height: 1.6;
      }}
      pre {{
        white-space: pre-wrap;
        word-break: break-word;
        margin: 0;
        font-size: 15px;
      }}
    </style>
  </head>
  <body>
    <pre>{safe_content}</pre>
  </body>
</html>
"""

