from django.conf import settings

from .auth import hash_password
from .db import get_db
from .seed_categories import CATEGORIES
from .catalog import build_products
from .utils import now


def _fill(text, brand):
    return text.replace("{brand}", brand) if isinstance(text, str) else text


def seed(reset=False, admin_email=None, admin_password=None, reprice=False, rewrite_content=False):
    db = get_db()
    brand = settings.SITE_NAME
    if reset:
        db.products.delete_many({})
        db.categories.delete_many({})
    created = {"categories": 0, "products": 0}
    for c in CATEGORIES:
        doc = {k: _fill(v, brand) for k, v in c.items() if k != "faqs"}
        doc["faqs"] = [{"q": _fill(f["q"], brand), "a": _fill(f["a"], brand)} for f in c["faqs"]]
        doc["active"] = True
        doc["updated_at"] = now()
        r = db.categories.update_one({"slug": c["slug"]}, {"$setOnInsert": {**doc, "created_at": now()}}, upsert=True)
        created["categories"] += 1 if r.upserted_id else 0
    for p in build_products(brand):
        p["sold"] = 0
        p["created_at"] = p["updated_at"] = now()
        if rewrite_content:
            # Replace the generated long-form description and FAQs (overwrites admin edits to those two fields only)
            db.products.update_one({"slug": p["slug"]}, {"$set": {"description": p["description"], "faqs": p["faqs"],
                                                                 "updated_at": now()}})
        if reprice:
            # Update price fields only; keeps any edits you made to text, stock or photos in the admin
            db.products.update_one({"slug": p["slug"]}, {"$set": {"price": p["price"], "compare_at": p["compare_at"],
                                                                 "source_price": p["source_price"], "updated_at": now()}})
        r = db.products.update_one({"slug": p["slug"]}, {"$setOnInsert": p}, upsert=True)
        created["products"] += 1 if r.upserted_id else 0
    if admin_email and admin_password:
        db.admins.update_one(
            {"email": admin_email.lower()},
            {"$set": {"password_hash": hash_password(admin_password), "active": True},
             "$setOnInsert": {"name": "Admin", "created_at": now()}},
            upsert=True,
        )
    return created
