#!/usr/bin/env python3
"""Seed demo Experience (Torbat Pages) data via service layer.

Run from repo root:
  cd backend/services/experience
  set AUTH_REQUIRED=false
  set EXPERIENCE_SEED_TENANT_ID=<your-tenant-uuid>
  python scripts/seed_experience.py

Or with PYTHONPATH:
  set PYTHONPATH=backend/services/experience;backend
  python backend/services/experience/scripts/seed_experience.py
"""
from __future__ import annotations

import asyncio
import os
import sys
import uuid

# Allow running without installing package
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if _ROOT not in sys.path:
    sys.path.insert(0, _ROOT)
_BACKEND = os.path.abspath(os.path.join(_ROOT, "..", ".."))
if _BACKEND not in sys.path:
    sys.path.insert(0, _BACKEND)
_SHARED = os.path.join(_BACKEND, "shared-lib")
if os.path.isdir(_SHARED) and _SHARED not in sys.path:
    sys.path.insert(0, _SHARED)

os.environ.setdefault("AUTH_REQUIRED", "false")

from app.core.database import AsyncSessionLocal  # noqa: E402
from app.models.types import LifecycleStatus, PageType, PublishStatus  # noqa: E402
from app.schemas.foundation import ExperienceWorkspaceCreate  # noqa: E402
from app.schemas.forms import ExperienceFormCreate  # noqa: E402
from app.schemas.sites import ExperiencePageCreate, ExperienceSiteCreate  # noqa: E402
from app.schemas.templates import ExperienceTemplateCreate  # noqa: E402
from app.services.foundation import ExperienceWorkspaceService  # noqa: E402
from app.services.forms import ExperienceFormService  # noqa: E402
from app.services.sites import ExperiencePageService, ExperienceSiteService  # noqa: E402
from app.services.templates import ExperienceTemplateService  # noqa: E402
from shared.security import CurrentUser  # noqa: E402


def _actor() -> CurrentUser:
    return CurrentUser(
        user_id="00000000-0000-0000-0000-000000000001",
        email="seed@torbatyar.local",
        username="seed",
        roles=["platform_admin"],
    )


async def seed() -> None:
    tenant_raw = os.environ.get("EXPERIENCE_SEED_TENANT_ID")
    if not tenant_raw:
        tenant_id = uuid.uuid4()
        print(f"EXPERIENCE_SEED_TENANT_ID not set — using generated tenant: {tenant_id}")
    else:
        tenant_id = uuid.UUID(tenant_raw)

    async with AsyncSessionLocal() as db:
        ws_svc = ExperienceWorkspaceService(db)
        site_svc = ExperienceSiteService(db)
        page_svc = ExperiencePageService(db)
        form_svc = ExperienceFormService(db)
        tpl_svc = ExperienceTemplateService(db)
        actor = _actor()

        ws = await ws_svc.create(
            tenant_id,
            ExperienceWorkspaceCreate(
                code="demo-ws",
                name="فضای کاری دمو",
                description="Seeded by seed_experience.py",
                status=LifecycleStatus.ACTIVE,
            ),
            actor=actor,
        )
        print(f"workspace: {ws.id}")

        site = await site_svc.create(
            tenant_id,
            ExperienceSiteCreate(
                workspace_id=ws.id,
                code="demo-site",
                name="سایت دمو",
                publish_status=PublishStatus.DRAFT,
            ),
            actor=actor,
        )
        print(f"site: {site.id}")

        page = await page_svc.create(
            tenant_id,
            ExperiencePageCreate(
                workspace_id=ws.id,
                site_id=site.id,
                code="home",
                slug="home",
                title="صفحه اصلی",
                page_type=PageType.LANDING,
            ),
            actor=actor,
        )
        print(f"page: {page.id}")

        form = await form_svc.create(
            tenant_id,
            ExperienceFormCreate(
                workspace_id=ws.id,
                site_id=site.id,
                page_id=page.id,
                code="contact",
                name="فرم تماس",
                form_schema_json={
                    "fields": [
                        {"name": "full_name", "type": "text", "label": "نام", "required": True},
                        {"name": "email", "type": "email", "label": "ایمیل", "required": True},
                    ]
                },
            ),
            actor=actor,
        )
        print(f"form: {form.id}")

        tpl = await tpl_svc.create(
            tenant_id,
            ExperienceTemplateCreate(
                workspace_id=ws.id,
                code="landing-starter",
                name="قالب لندینگ",
                page_type="landing",
            ),
            actor=actor,
        )
        print(f"template: {tpl.id}")

        await db.commit()
        print("Seed complete.")
        print(f"Use X-Tenant-ID: {tenant_id}")


if __name__ == "__main__":
    asyncio.run(seed())
