#!/usr/bin/env python3
"""
Simple diet logging skill - accepts natural language input.

Usage examples:
    "log diet: 中午12点吃了鸡胸肉沙拉，大约500卡"
    "log diet: 晚上7点OMAD，吃了牛排和蔬菜"
    "log diet: 早餐8点燕麦粥"
"""

import sys
import re
from datetime import datetime, date
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from health.services.manual_log_storage import ManualLogStorage
from health.models.manual_log import DietEntry


def parse_diet_input(text: str) -> dict:
    """Parse natural language diet input.

    Returns:
        dict with keys: time, description, meal_type, estimated_calories, carbs, notes
    """
    result = {
        "time": None,
        "description": text,
        "meal_type": None,
        "estimated_calories": None,
        "carbs": None,
        "notes": None,
    }

    # Extract time (HH:MM or descriptive)
    # Try HH:MM format first
    time_match = re.search(r'(\d{1,2})[:\.](\d{2})', text)
    if time_match:
        hour, minute = time_match.groups()
        result["time"] = f"{int(hour):02d}:{minute}"
    # Try "X点" format
    elif re.search(r'(\d{1,2})点', text):
        hour = re.search(r'(\d{1,2})点', text).group(1)
        result["time"] = f"{int(hour):02d}:00"
    else:
        # Try to extract meal time descriptors
        if any(word in text for word in ['早上', '早餐', '早饭']):
            result["time"] = "08:00"
            result["meal_type"] = "breakfast"
        elif any(word in text for word in ['中午', '午餐', '午饭']):
            result["time"] = "12:00"
            result["meal_type"] = "lunch"
        elif any(word in text for word in ['晚上', '晚餐', '晚饭']):
            result["time"] = "19:00"
            result["meal_type"] = "dinner"
        else:
            result["time"] = datetime.now().strftime("%H:%M")

    # Extract calories (must have "卡" or "cal" nearby)
    cal_match = re.search(r'(\d+)\s*卡', text)
    if not cal_match:
        cal_match = re.search(r'(\d+)\s*cal', text, re.IGNORECASE)
    if cal_match:
        result["estimated_calories"] = int(cal_match.group(1))

    # Extract meal type if not already set
    if not result["meal_type"]:
        if any(word in text for word in ['早餐', '早饭']):
            result["meal_type"] = "breakfast"
        elif any(word in text for word in ['午餐', '午饭', '中餐']):
            result["meal_type"] = "lunch"
        elif any(word in text for word in ['晚餐', '晚饭']):
            result["meal_type"] = "dinner"
        elif '零食' in text or '加餐' in text:
            result["meal_type"] = "snack"

    # Extract carb info
    if any(word in text for word in ['低碳', '生酮', 'keto']):
        result["carbs"] = "Low"
    elif any(word in text for word in ['高碳', '碳水']):
        result["carbs"] = "High"

    # Check for OMAD
    if 'OMAD' in text or 'omad' in text:
        result["notes"] = "OMAD"

    # Check for PSMF
    if 'PSMF' in text or 'psmf' in text:
        result["notes"] = "PSMF"

    return result


def main() -> int:
    """Main function."""
    if len(sys.argv) < 2:
        print("❌ Please provide diet description")
        print("Example: python log_diet_simple.py '中午12点吃了鸡胸肉沙拉，500卡'")
        return 1

    text = " ".join(sys.argv[1:])

    try:
        storage = ManualLogStorage()
        today = date.today()

        # Parse input
        parsed = parse_diet_input(text)

        if not parsed["time"]:
            print("❌ Could not determine time. Please specify time or meal period.")
            return 1

        # Create entry
        entry = DietEntry(
            time=parsed["time"],
            description=parsed["description"],
            meal_type=parsed["meal_type"],
            estimated_calories=parsed["estimated_calories"],
            carbs=parsed["carbs"],
            notes=parsed["notes"],
        )

        # Save
        storage.add_diet_entry(today, entry)

        print(f"✅ Diet entry added for {today}")
        print(f"   Time: {entry.time}")
        print(f"   Description: {entry.description}")
        if entry.meal_type:
            print(f"   Type: {entry.meal_type}")
        if entry.estimated_calories:
            print(f"   Calories: {entry.estimated_calories}")

        return 0

    except Exception as e:
        print(f"❌ Failed to add diet entry: {e}")
        import traceback
        traceback.print_exc()
        return 1


if __name__ == "__main__":
    sys.exit(main())
