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

Usage examples:
    "log supplement: 早上8点吃了Fish Oil和Berberine"
    "log supplement: 睡前吃了Magnesium 400mg"
    "log supplement: NAC、CoQ10、Vitamin D"
"""

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 SupplementEntry


# Common supplement name mappings
SUPPLEMENT_MAPPINGS = {
    "鱼油": "Fish Oil",
    "辅酶": "CoQ10",
    "辅酶q10": "CoQ10",
    "q10": "CoQ10",
    "镁": "Magnesium",
    "小檗碱": "Berberine",
    "黄连素": "Berberine",
    "b族": "Vitamin B Complex",
    "维生素b": "Vitamin B Complex",
    "d3": "Vitamin D3+K2",
    "维生素d": "Vitamin D3+K2",
    "vd": "Vitamin D3+K2",
}


def parse_supplement_input(text: str) -> list[dict]:
    """Parse natural language supplement input.

    Returns:
        list of dicts with keys: time, supplement_name, dosage, timing
    """
    results = []

    # Extract time
    time_match = re.search(r'(\d{1,2})[:\.](\d{2})', text)
    if time_match:
        hour, minute = time_match.groups()
        time = f"{int(hour):02d}:{minute}"
        timing = None
    elif re.search(r'(\d{1,2})点', text):
        hour = re.search(r'(\d{1,2})点', text).group(1)
        time = f"{int(hour):02d}:00"
        timing = None
    else:
        # Try to extract timing descriptors
        if any(word in text for word in ['早上', '早晨', '早餐']):
            time = "08:00"
            timing = "morning"
        elif any(word in text for word in ['下午', '午后']):
            time = "15:00"
            timing = "afternoon"
        elif any(word in text for word in ['晚上', '晚餐']):
            time = "19:00"
            timing = "evening"
        elif any(word in text for word in ['睡前', '就寝']):
            time = "22:00"
            timing = "before_bed"
        else:
            time = datetime.now().strftime("%H:%M")
            timing = None

    # Extract supplement names (split by common separators)
    # Remove time and dosage info first
    text_clean = re.sub(r'\d{1,2}[:\.]?\d{2}', '', text)  # Remove HH:MM
    text_clean = re.sub(r'\d{1,2}点', '', text_clean)  # Remove X点
    text_clean = re.sub(r'早上|晚上|中午|睡前|吃了|服用', '', text_clean)

    # Split by separators
    separators = ['、', '和', ',', '，', '以及', '\n']
    parts = [text_clean]
    for sep in separators:
        new_parts = []
        for part in parts:
            new_parts.extend(part.split(sep))
        parts = new_parts

    for part in parts:
        part = part.strip()
        if not part or len(part) < 2:
            continue

        # Extract dosage if present
        dosage = None
        dosage_match = re.search(r'(\d+\.?\d*)\s*(mg|g|粒|片|ml)', part)
        if dosage_match:
            dosage = dosage_match.group(0)
            part = re.sub(r'\d+\.?\d*\s*(mg|g|粒|片|ml)', '', part).strip()

        # Normalize supplement name
        supp_name = part
        part_lower = part.lower()
        for cn, en in SUPPLEMENT_MAPPINGS.items():
            if cn in part_lower:
                supp_name = en
                break

        if supp_name:
            results.append({
                "time": time,
                "supplement_name": supp_name,
                "dosage": dosage,
                "timing": timing,
            })

    return results


def main() -> int:
    """Main function."""
    if len(sys.argv) < 2:
        print("❌ Please provide supplement description")
        print("Example: python log_supplement_simple.py '早上吃了Fish Oil和Berberine'")
        return 1

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

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

        # Parse input
        parsed_list = parse_supplement_input(text)

        if not parsed_list:
            print("❌ Could not extract supplement names")
            return 1

        # Add all entries
        for parsed in parsed_list:
            entry = SupplementEntry(
                time=parsed["time"],
                supplement_name=parsed["supplement_name"],
                dosage=parsed["dosage"],
                timing=parsed["timing"],
                notes=None,
            )
            storage.add_supplement_entry(today, entry)

            print(f"✅ Added: {entry.supplement_name} at {entry.time}", end="")
            if entry.dosage:
                print(f" ({entry.dosage})", end="")
            print()

        print(f"\n📊 Total: {len(parsed_list)} supplements logged for {today}")
        return 0

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


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