#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Demo Quality Templates Seeding Script for Production Service
Creates quality check templates for demo template tenants

This script runs as a Kubernetes init job inside the production-service container.
"""

import asyncio
import uuid
import sys
import os
import json
from datetime import datetime, timezone
from pathlib import Path

# Add app to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select
import structlog

from app.models.production import QualityCheckTemplate

# Configure logging
logger = structlog.get_logger()

# Base demo tenant IDs
DEMO_TENANT_SAN_PABLO = uuid.UUID("a1b2c3d4-e5f6-47a8-b9c0-d1e2f3a4b5c6")  # Individual bakery
DEMO_TENANT_LA_ESPIGA = uuid.UUID("b2c3d4e5-f6a7-48b9-c0d1-e2f3a4b5c6d7")  # Central bakery

# System user ID (first admin user from auth service)
SYSTEM_USER_ID = uuid.UUID("50000000-0000-0000-0000-000000000004")

# Base reference date for date calculations
BASE_REFERENCE_DATE = datetime(2025, 1, 15, 12, 0, 0, tzinfo=timezone.utc)


def load_quality_templates_data():
    """Load quality templates data from JSON file"""
    data_file = Path(__file__).parent / "plantillas_calidad_es.json"
    if not data_file.exists():
        raise FileNotFoundError(f"Quality templates data file not found: {data_file}")

    with open(data_file, 'r', encoding='utf-8') as f:
        return json.load(f)


# Model uses simple strings, no need for enum mapping functions


async def seed_quality_templates_for_tenant(
    db: AsyncSession,
    tenant_id: uuid.UUID,
    tenant_name: str,
    templates_list: list
):
    """Seed quality templates for a specific tenant"""
    logger.info(f"Seeding quality templates for: {tenant_name}", tenant_id=str(tenant_id))

    # Check if templates already exist
    result = await db.execute(
        select(QualityCheckTemplate).where(QualityCheckTemplate.tenant_id == tenant_id).limit(1)
    )
    existing = result.scalar_one_or_none()

    if existing:
        logger.info(f"Quality templates already exist for {tenant_name}, skipping seed")
        return {"tenant_id": str(tenant_id), "templates_created": 0, "skipped": True}

    count = 0
    for template_data in templates_list:
        # Use strings directly (model doesn't use enums)
        check_type = template_data["check_type"]
        applicable_stages = template_data.get("applicable_stages", [])

        # For San Pablo, use original IDs. For La Espiga, generate new UUIDs
        if tenant_id == DEMO_TENANT_SAN_PABLO:
            template_id = uuid.UUID(template_data["id"])
        else:
            # Generate deterministic UUID for La Espiga based on original ID
            base_uuid = uuid.UUID(template_data["id"])
            # Add a fixed offset to create a unique but deterministic ID
            template_id = uuid.UUID(int=base_uuid.int + 0x10000000000000000000000000000000)

        # Create quality check template
        template = QualityCheckTemplate(
            id=template_id,
            tenant_id=tenant_id,
            name=template_data["name"],
            template_code=template_data["template_code"],
            check_type=check_type,
            category=template_data.get("category"),
            description=template_data.get("description"),
            instructions=template_data.get("instructions"),
            parameters=template_data.get("parameters"),
            thresholds=template_data.get("thresholds"),
            scoring_criteria=template_data.get("scoring_criteria"),
            is_active=template_data.get("is_active", True),
            is_required=template_data.get("is_required", False),
            is_critical=template_data.get("is_critical", False),
            weight=template_data.get("weight", 1.0),
            min_value=template_data.get("min_value"),
            max_value=template_data.get("max_value"),
            target_value=template_data.get("target_value"),
            unit=template_data.get("unit"),
            tolerance_percentage=template_data.get("tolerance_percentage"),
            applicable_stages=applicable_stages,
            created_by=SYSTEM_USER_ID,
            created_at=BASE_REFERENCE_DATE,
            updated_at=BASE_REFERENCE_DATE
        )

        db.add(template)
        count += 1
        logger.debug(f"Created quality template: {template.name}", template_id=str(template.id))

    await db.commit()
    logger.info(f"Successfully created {count} quality templates for {tenant_name}")

    return {
        "tenant_id": str(tenant_id),
        "templates_created": count,
        "skipped": False
    }


async def seed_all(db: AsyncSession):
    """Seed all demo tenants with quality templates"""
    logger.info("Starting demo quality templates seed process")

    # Load quality templates data
    data = load_quality_templates_data()

    results = []

    # Both tenants get the same quality templates
    result_san_pablo = await seed_quality_templates_for_tenant(
        db,
        DEMO_TENANT_SAN_PABLO,
        "San Pablo - Individual Bakery",
        data["plantillas_calidad"]
    )
    results.append(result_san_pablo)

    result_la_espiga = await seed_quality_templates_for_tenant(
        db,
        DEMO_TENANT_LA_ESPIGA,
        "La Espiga - Central Bakery",
        data["plantillas_calidad"]
    )
    results.append(result_la_espiga)

    total_created = sum(r["templates_created"] for r in results)

    return {
        "results": results,
        "total_templates_created": total_created,
        "status": "completed"
    }


async def main():
    """Main execution function"""
    # Get database URL from environment
    database_url = os.getenv("PRODUCTION_DATABASE_URL")
    if not database_url:
        logger.error("PRODUCTION_DATABASE_URL environment variable must be set")
        return 1

    # Ensure asyncpg driver
    if database_url.startswith("postgresql://"):
        database_url = database_url.replace("postgresql://", "postgresql+asyncpg://", 1)

    # Create async engine
    engine = create_async_engine(database_url, echo=False)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    try:
        async with async_session() as session:
            result = await seed_all(session)

            logger.info(
                "Quality templates seed completed successfully!",
                total_templates=result["total_templates_created"],
                status=result["status"]
            )

            # Print summary
            print("\n" + "="*60)
            print("DEMO QUALITY TEMPLATES SEED SUMMARY")
            print("="*60)
            for tenant_result in result["results"]:
                tenant_id = tenant_result["tenant_id"]
                count = tenant_result["templates_created"]
                skipped = tenant_result.get("skipped", False)
                status = "SKIPPED (already exists)" if skipped else f"CREATED {count} templates"
                print(f"Tenant {tenant_id}: {status}")
            print(f"\nTotal Templates Created: {result['total_templates_created']}")
            print("="*60 + "\n")

            return 0

    except Exception as e:
        logger.error(f"Quality templates seed failed: {str(e)}", exc_info=True)
        return 1
    finally:
        await engine.dispose()


if __name__ == "__main__":
    exit_code = asyncio.run(main())
    sys.exit(exit_code)
