"""
Cemetery public pages content seeder — Riverside Memorial Park demo data.

CLI tool only — must never be exposed as an API endpoint.

Usage:
    python -m src.database.seeders.page_content_seeder
    python -m src.database.seeders.page_content_seeder --tenant-slug riverside

Optional env override:
    SEED_TENANT_SLUG=riverside python -m src.database.seeders.page_content_seeder
"""

import argparse
import asyncio
import os
import sys

from sqlalchemy import select, text

from src.database.load_models import load_all_models

load_all_models()

from src.database.session import AsyncSessionLocal as async_session_factory  # noqa: E402
from src.apps.pages.models.page_content import TenantPageContent  # noqa: E402

DEMO_SLUG = os.getenv("SEED_TENANT_SLUG", "riverside")

# ── Seed payloads ─────────────────────────────────────────────────────────────

GLOBAL_CONTENT = {
    "phone_main": "(613) 555-0142",
    "phone_afterhours": "(613) 555-0199",
    "email": "office@riverside-memorial.ca",
    "address_street": "1247 Riverside Drive",
    "address_city": "Ottawa",
    "address_province": "ON",
    "address_postal": "K1H 8L9",
    "hours_grounds": "7 am - sunset, daily",
    "hours_office_weekday": "Mon-Fri 8:30 am - 4:30 pm",
    "hours_office_saturday": "By appointment Sat AM",
    "total_hectares": 32.0,
    "lat": 45.377000,
    "lng": -75.697500,
}

FIND_CONTENT = {
    "hero_headline": "Find a loved one",
    "hero_subtitle": (
        "Search burial and memorial records at Riverside Memorial Park. "
        "We'll show you where they rest, walking directions to the plot, "
        "and any memorial the family has chosen to make public."
    ),
    "context_bar_text": "memorials on file - back to",
    "footer_note": (
        "Records are searchable back to 1887. "
        "About 38% of memorials have public pages - "
        "families control what's visible."
    ),
    "ai_chips": [
        "My grandfather, served in WWII, passed in the late 1990s",
        "A woman named Margaret who lived on Elgin Street",
        "Someone buried in Section B last spring",
    ],
}

AVAILABILITY_CONTENT = {
    "hero_headline": "Plot availability",
    "hero_lead": (
        "Browse what we currently have available at Riverside Memorial Park - "
        "burial plots, family vaults, and columbarium niches. "
        "Send a no-obligation inquiry and our office will walk you through "
        "pricing, location, and pre-need planning."
    ),
    "no_checkout_notice": (
        "No online checkout - every plot is reserved through our office "
        "so you can ask questions and visit in person first."
    ),
}

MAP_CONTENT = {
    "hero_eyebrow": "Walking guide",
    "hero_headline": "Cemetery map",
    "hero_subtitle": (
        "Find your way around the grounds. Each section has its own character - "
        "pick one to learn more, or use Find a loved one to look up a specific plot."
    ),
    "map_image_url": None,
    "map_pdf_en_url": None,
    "map_pdf_fr_url": None,
    "section_pins": {
        "A": {"x": 25, "y": 40},
        "B": {"x": 65, "y": 55},
        "C": {"x": 45, "y": 70},
        "D": {"x": 30, "y": 20},
    },
}

CONTACT_CONTENT = {
    "hero_headline": "Visit, call, or send us a note",
    "hero_subtitle": (
        "Our office staff are here to help - whether you're planning ahead, "
        "arranging a service, looking up a family record, or just need directions "
        "before a visit."
    ),
    "gate1_description": (
        "Cemetery office, visitor parking, accessible path. Use this entrance "
        "for office visits, record pickup, and most plot locations."
    ),
    "gate2_description": (
        "Chapel and columbarium. Use this entrance if you're attending a service."
    ),
    "transit_route": "Route 7",
    "transit_stop": "Riverside & Bank",
    "transit_walk_time": "4-minute walk to gate 1",
    "parking_note": (
        "Free visitor parking at both gates. Accessible spaces at gate 1."
    ),
    "accessibility_note": (
        "A complimentary motorised cart is available from the gatehouse on request."
    ),
}

PAGES = [
    ("global", GLOBAL_CONTENT),
    ("find", FIND_CONTENT),
    ("availability", AVAILABILITY_CONTENT),
    ("map", MAP_CONTENT),
    ("contact", CONTACT_CONTENT),
]


# ── Runner ────────────────────────────────────────────────────────────────────

async def seed(tenant_slug: str) -> None:
    async with async_session_factory() as db:
        row = await db.execute(
            text("SELECT id FROM accounts WHERE subdomain = :slug LIMIT 1"),
            {"slug": tenant_slug},
        )
        tenant = row.fetchone()
        if not tenant:
            print(f"[seeder] ERROR: tenant with slug '{tenant_slug}' not found.")
            sys.exit(1)

        tenant_id = tenant[0]
        print(f"[seeder] Seeding page content for tenant: {tenant_slug} ({tenant_id})")

        for slug, payload in PAGES:
            existing = await db.execute(
                select(TenantPageContent).where(
                    TenantPageContent.tenant_id == tenant_id,
                    TenantPageContent.page_slug == slug,
                )
            )
            row_obj = existing.scalar_one_or_none()
            if row_obj is None:
                db.add(TenantPageContent(tenant_id=tenant_id, page_slug=slug, content=payload))
            else:
                row_obj.content = payload
            print(f"[seeder]   OK  {slug}")

        await db.commit()
        print("[seeder] Done.")


def main() -> None:
    parser = argparse.ArgumentParser(description="Seed cemetery page content.")
    parser.add_argument(
        "--tenant-slug",
        default=DEMO_SLUG,
        help="Slug of the tenant to seed (default: $SEED_TENANT_SLUG or 'riverside')",
    )
    args = parser.parse_args()
    asyncio.run(seed(args.tenant_slug))


if __name__ == "__main__":
    main()
