# File: plugins/cli/seed.py

import click
from flask.cli import with_appcontext
from datetime import datetime, timedelta

from app import db
from plugins.auth.models import User
from plugins.plant.models import (
    Plant,
    PlantCommonName,
    PlantScientificName
)

@click.command(name='preload-data')
@with_appcontext
def preload_data_cli():
    preload_data(auto=False)

def preload_data(auto=False):
    if User.query.filter_by(email='admin@example.com').first():
        if not auto:
            click.echo("⚠️  Demo data already exists, skipping.")
        return

    if not auto:
        click.echo("🌱 Seeding demo data...")

    # USERS
    admin = User(
        username='admin',
        email='admin@example.com',
        role='admin',
        is_verified=True
    )
    admin.set_password('password123')

    user = User(
        username='user',
        email='user@example.com',
        role='user',
        is_verified=True
    )
    user.set_password('password123')

    db.session.add_all([admin, user])
    db.session.commit()

    # COMMON & SCIENTIFIC NAMES
    joepii_common = PlantCommonName(name='Philodendron Joepii')
    queen_common = PlantCommonName(name='Anthurium Warocqueanum Queen')
    thai_common = PlantCommonName(name='Thai Constellation Monstera')
    generic_common = PlantCommonName(name='Monstera')

    db.session.add_all([joepii_common, queen_common, thai_common, generic_common])
    db.session.flush()  # ensures all common_name IDs are available

    joepii_sci = PlantScientificName(
        name='Philodendron × joepii',
        common_id=joepii_common.id
    )
    queen_sci = PlantScientificName(
        name='Anthurium warocqueanum',
        common_id=queen_common.id
    )
    thai_sci = PlantScientificName(
        name="Monstera deliciosa 'Thai Constellation'",
        common_id=thai_common.id
    )
    generic_sci = PlantScientificName(
        name='Monstera deliciosa',
        common_id=generic_common.id
    )

    db.session.add_all([joepii_sci, queen_sci, thai_sci, generic_sci])
    db.session.commit()

    if not auto:
        click.echo("🎉 Demo data seeded successfully.")
