"""
CLI tool for manual health data entry.
"""

import sys
from datetime import date
from typing import Optional

import click

from health.services.manual_log_storage import ManualLogStorage
from health.models.manual_log import (
    DietEntry,
    AlcoholEntry,
    SupplementEntry,
    BodyFeelingEntry,
)
from health.utils.date_utils import parse_date
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)


@click.group()
def cli() -> None:
    """Manual Health Data Entry CLI."""
    pass


def _get_date(date_str: Optional[str]) -> date:
    """Parse date string or return today."""
    if date_str:
        return parse_date(date_str)
    return date.today()


@cli.command()
@click.option("--time", required=True, help="Time of meal (HH:MM)")
@click.option("--desc", required=True, help="Description of what was eaten")
@click.option("--type", "meal_type", help="Meal type (breakfast/lunch/dinner/snack)")
@click.option("--cals", type=int, help="Estimated calories")
@click.option("--carbs", help="Carb content (Low/Medium/High)")
@click.option("--notes", help="Additional notes")
@click.option("--date", "date_str", help="Date of entry (YYYY-MM-DD)")
def diet(
    time: str,
    desc: str,
    meal_type: Optional[str],
    cals: Optional[int],
    carbs: Optional[str],
    notes: Optional[str],
    date_str: Optional[str],
) -> None:
    """Add a diet entry."""
    try:
        storage = ManualLogStorage()
        target_date = _get_date(date_str)

        entry = DietEntry(
            time=time,
            description=desc,
            meal_type=meal_type,
            estimated_calories=cals,
            carbs=carbs,
            notes=notes,
        )

        storage.add_diet_entry(target_date, entry)
        click.echo(f"✅ Added diet entry for {target_date}: {desc}")

    except Exception as e:
        click.echo(f"❌ Failed to add diet entry: {e}", err=True)
        sys.exit(1)


@cli.command()
@click.option("--time", required=True, help="Time of consumption (HH:MM)")
@click.option("--type", "drink_type", required=True, help="Type of alcohol")
@click.option("--amount", required=True, help="Amount consumed")
@click.option("--food", help="Food eaten with alcohol")
@click.option("--nac", is_flag=True, help="NAC taken?")
@click.option("--notes", help="Additional notes")
@click.option("--date", "date_str", help="Date of entry (YYYY-MM-DD)")
def alcohol(
    time: str,
    drink_type: str,
    amount: str,
    food: Optional[str],
    nac: bool,
    notes: Optional[str],
    date_str: Optional[str],
) -> None:
    """Add an alcohol entry."""
    try:
        storage = ManualLogStorage()
        target_date = _get_date(date_str)

        entry = AlcoholEntry(
            time=time,
            drink_type=drink_type,
            amount=amount,
            food_with_alcohol=food,
            nac_taken=nac,
            notes=notes,
        )

        storage.add_alcohol_entry(target_date, entry)
        click.echo(f"✅ Added alcohol entry for {target_date}: {drink_type}")

    except Exception as e:
        click.echo(f"❌ Failed to add alcohol entry: {e}", err=True)
        sys.exit(1)


@cli.command()
@click.option("--time", required=True, help="Time taken (HH:MM)")
@click.option("--name", required=True, help="Supplement name")
@click.option("--dosage", help="Dosage")
@click.option("--timing", help="Timing (morning/evening used for sorting)")
@click.option("--notes", help="Additional notes")
@click.option("--date", "date_str", help="Date of entry (YYYY-MM-DD)")
def supp(
    time: str,
    name: str,
    dosage: Optional[str],
    timing: Optional[str],
    notes: Optional[str],
    date_str: Optional[str],
) -> None:
    """Add a supplement entry."""
    try:
        storage = ManualLogStorage()
        target_date = _get_date(date_str)

        entry = SupplementEntry(
            time=time,
            supplement_name=name,
            dosage=dosage,
            timing=timing,
            notes=notes,
        )

        storage.add_supplement_entry(target_date, entry)
        click.echo(f"✅ Added supplement entry for {target_date}: {name}")

    except Exception as e:
        click.echo(f"❌ Failed to add supplement entry: {e}", err=True)
        sys.exit(1)


@cli.command()
@click.option("--time", required=True, help="Time of feeling (HH:MM)")
@click.option("--type", "feeling_type", required=True, help="Type of feeling")
@click.option("--desc", required=True, help="Description")
@click.option("--severity", type=int, help="Severity (1-10)")
@click.option("--loc", "location", help="Body location")
@click.option("--triggers", help="Possible triggers")
@click.option("--notes", help="Additional notes")
@click.option("--date", "date_str", help="Date of entry (YYYY-MM-DD)")
def feeling(
    time: str,
    feeling_type: str,
    desc: str,
    severity: Optional[int],
    location: Optional[str],
    triggers: Optional[str],
    notes: Optional[str],
    date_str: Optional[str],
) -> None:
    """Add a body feeling/symptom entry."""
    try:
        storage = ManualLogStorage()
        target_date = _get_date(date_str)

        entry = BodyFeelingEntry(
            time=time,
            feeling_type=feeling_type,
            description=desc,
            severity=severity,
            location=location,
            triggers=triggers,
            notes=notes,
        )

        storage.add_feeling_entry(target_date, entry)
        click.echo(f"✅ Added feeling entry for {target_date}: {feeling_type}")

    except Exception as e:
        click.echo(f"❌ Failed to add feeling entry: {e}", err=True)
        sys.exit(1)


@cli.command()
@click.option("--mode", required=True, help="Fasting mode (OMAD/PSMF/etc)")
@click.option("--date", "date_str", help="Date of entry (YYYY-MM-DD)")
def fasting(mode: str, date_str: Optional[str]) -> None:
    """Set fasting mode for a day."""
    try:
        storage = ManualLogStorage()
        target_date = _get_date(date_str)

        storage.set_fasting_mode(target_date, mode)
        click.echo(f"✅ Set fasting mode for {target_date}: {mode}")

    except Exception as e:
        click.echo(f"❌ Failed to set fasting mode: {e}", err=True)
        sys.exit(1)


if __name__ == "__main__":
    cli()
