"""
Internal Demo Cloning API for Orders Service
Service-to-service endpoint for cloning order and customer data
"""

from fastapi import APIRouter, Depends, HTTPException, Header
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete, func
import structlog
import uuid
from datetime import datetime, timezone, timedelta, date
from typing import Optional
import os
from decimal import Decimal

from app.core.database import get_db
from app.models.order import CustomerOrder, OrderItem
from app.models.customer import Customer
from shared.utils.demo_dates import adjust_date_for_demo, BASE_REFERENCE_DATE

logger = structlog.get_logger()
router = APIRouter(prefix="/internal/demo", tags=["internal"])

# Internal API key for service-to-service auth
INTERNAL_API_KEY = os.getenv("INTERNAL_API_KEY", "dev-internal-key-change-in-production")

# Base demo tenant IDs
DEMO_TENANT_SAN_PABLO = "a1b2c3d4-e5f6-47a8-b9c0-d1e2f3a4b5c6"
DEMO_TENANT_LA_ESPIGA = "b2c3d4e5-f6a7-48b9-c0d1-e2f3a4b5c6d7"


def verify_internal_api_key(x_internal_api_key: Optional[str] = Header(None)):
    """Verify internal API key for service-to-service communication"""
    if x_internal_api_key != INTERNAL_API_KEY:
        logger.warning("Unauthorized internal API access attempted")
        raise HTTPException(status_code=403, detail="Invalid internal API key")
    return True


@router.post("/clone")
async def clone_demo_data(
    base_tenant_id: str,
    virtual_tenant_id: str,
    demo_account_type: str,
    session_id: Optional[str] = None,
    session_created_at: Optional[str] = None,
    db: AsyncSession = Depends(get_db),
    _: bool = Depends(verify_internal_api_key)
):
    """
    Clone orders service data for a virtual demo tenant

    Clones:
    - Customers
    - Customer orders with line items
    - Adjusts dates to recent timeframe

    Args:
        base_tenant_id: Template tenant UUID to clone from
        virtual_tenant_id: Target virtual tenant UUID
        demo_account_type: Type of demo account
        session_id: Originating session ID for tracing

    Returns:
        Cloning status and record counts
    """
    start_time = datetime.now(timezone.utc)

    # Parse session creation time for date adjustment
    if session_created_at:
        try:
            session_time = datetime.fromisoformat(session_created_at.replace('Z', '+00:00'))
        except (ValueError, AttributeError):
            session_time = start_time
    else:
        session_time = start_time

    logger.info(
        "Starting orders data cloning",
        base_tenant_id=base_tenant_id,
        virtual_tenant_id=virtual_tenant_id,
        demo_account_type=demo_account_type,
        session_id=session_id,
        session_created_at=session_created_at
    )

    try:
        # Validate UUIDs
        base_uuid = uuid.UUID(base_tenant_id)
        virtual_uuid = uuid.UUID(virtual_tenant_id)

        # Track cloning statistics
        stats = {
            "customers": 0,
            "customer_orders": 0,
            "order_line_items": 0,
            "alerts_generated": 0
        }

        # Customer ID mapping (old -> new)
        customer_id_map = {}

        # Clone Customers
        result = await db.execute(
            select(Customer).where(Customer.tenant_id == base_uuid)
        )
        base_customers = result.scalars().all()

        logger.info(
            "Found customers to clone",
            count=len(base_customers),
            base_tenant=str(base_uuid)
        )

        for customer in base_customers:
            new_customer_id = uuid.uuid4()
            customer_id_map[customer.id] = new_customer_id

            new_customer = Customer(
                id=new_customer_id,
                tenant_id=virtual_uuid,
                customer_code=customer.customer_code,
                name=customer.name,
                business_name=customer.business_name,
                customer_type=customer.customer_type,
                tax_id=customer.tax_id,
                email=customer.email,
                phone=customer.phone,
                address_line1=customer.address_line1,
                address_line2=customer.address_line2,
                city=customer.city,
                state=customer.state,
                postal_code=customer.postal_code,
                country=customer.country,
                business_license=customer.business_license,
                is_active=customer.is_active,
                preferred_delivery_method=customer.preferred_delivery_method,
                payment_terms=customer.payment_terms,
                credit_limit=customer.credit_limit,
                discount_percentage=customer.discount_percentage,
                customer_segment=customer.customer_segment,
                priority_level=customer.priority_level,
                special_instructions=customer.special_instructions,
                delivery_preferences=customer.delivery_preferences,
                product_preferences=customer.product_preferences,
                total_orders=customer.total_orders,
                total_spent=customer.total_spent,
                average_order_value=customer.average_order_value,
                last_order_date=customer.last_order_date,
                created_at=session_time,
                updated_at=session_time
            )
            db.add(new_customer)
            stats["customers"] += 1

        # Clone Customer Orders with Line Items
        result = await db.execute(
            select(CustomerOrder).where(CustomerOrder.tenant_id == base_uuid)
        )
        base_orders = result.scalars().all()

        logger.info(
            "Found customer orders to clone",
            count=len(base_orders),
            base_tenant=str(base_uuid)
        )

        order_id_map = {}

        for order in base_orders:
            new_order_id = uuid.uuid4()
            order_id_map[order.id] = new_order_id

            # Adjust dates using demo_dates utility
            adjusted_order_date = adjust_date_for_demo(
                order.order_date, session_time, BASE_REFERENCE_DATE
            )
            adjusted_requested_delivery = adjust_date_for_demo(
                order.requested_delivery_date, session_time, BASE_REFERENCE_DATE
            )
            adjusted_confirmed_delivery = adjust_date_for_demo(
                order.confirmed_delivery_date, session_time, BASE_REFERENCE_DATE
            )
            adjusted_actual_delivery = adjust_date_for_demo(
                order.actual_delivery_date, session_time, BASE_REFERENCE_DATE
            )
            adjusted_window_start = adjust_date_for_demo(
                order.delivery_window_start, session_time, BASE_REFERENCE_DATE
            )
            adjusted_window_end = adjust_date_for_demo(
                order.delivery_window_end, session_time, BASE_REFERENCE_DATE
            )

            new_order = CustomerOrder(
                id=new_order_id,
                tenant_id=virtual_uuid,
                order_number=f"ORD-{uuid.uuid4().hex[:8].upper()}",  # New order number
                customer_id=customer_id_map.get(order.customer_id, order.customer_id),
                status=order.status,
                order_type=order.order_type,
                priority=order.priority,
                order_date=adjusted_order_date,
                requested_delivery_date=adjusted_requested_delivery,
                confirmed_delivery_date=adjusted_confirmed_delivery,
                actual_delivery_date=adjusted_actual_delivery,
                delivery_method=order.delivery_method,
                delivery_address=order.delivery_address,
                delivery_instructions=order.delivery_instructions,
                delivery_window_start=adjusted_window_start,
                delivery_window_end=adjusted_window_end,
                subtotal=order.subtotal,
                tax_amount=order.tax_amount,
                discount_amount=order.discount_amount,
                discount_percentage=order.discount_percentage,
                delivery_fee=order.delivery_fee,
                total_amount=order.total_amount,
                payment_status=order.payment_status,
                payment_method=order.payment_method,
                payment_terms=order.payment_terms,
                payment_due_date=order.payment_due_date,
                special_instructions=order.special_instructions,
                order_source=order.order_source,
                sales_channel=order.sales_channel,
                created_at=session_time,
                updated_at=session_time
            )
            db.add(new_order)
            stats["customer_orders"] += 1

        # Clone Order Items
        for old_order_id, new_order_id in order_id_map.items():
            result = await db.execute(
                select(OrderItem).where(OrderItem.order_id == old_order_id)
            )
            order_items = result.scalars().all()

            for item in order_items:
                new_item = OrderItem(
                    id=uuid.uuid4(),
                    order_id=new_order_id,
                    product_id=item.product_id,
                    product_name=item.product_name,
                    product_sku=item.product_sku,
                    quantity=item.quantity,
                    unit_of_measure=item.unit_of_measure,
                    unit_price=item.unit_price,
                    line_discount=item.line_discount,
                    line_total=item.line_total,
                    status=item.status
                )
                db.add(new_item)
                stats["order_line_items"] += 1

        # Commit cloned data
        await db.commit()

        # NOTE: Alert generation removed - alerts are now generated automatically by the
        # respective alert services which run scheduled checks at appropriate intervals.
        # This eliminates duplicate alerts and provides a more realistic demo experience.
        stats["alerts_generated"] = 0

        total_records = stats["customers"] + stats["customer_orders"] + stats["order_line_items"]
        duration_ms = int((datetime.now(timezone.utc) - start_time).total_seconds() * 1000)

        logger.info(
            "Orders data cloning completed",
            virtual_tenant_id=virtual_tenant_id,
            total_records=total_records,
            stats=stats,
            duration_ms=duration_ms
        )

        return {
            "service": "orders",
            "status": "completed",
            "records_cloned": total_records,
            "duration_ms": duration_ms,
            "details": stats
        }

    except ValueError as e:
        logger.error("Invalid UUID format", error=str(e))
        raise HTTPException(status_code=400, detail=f"Invalid UUID: {str(e)}")

    except Exception as e:
        logger.error(
            "Failed to clone orders data",
            error=str(e),
            virtual_tenant_id=virtual_tenant_id,
            exc_info=True
        )

        # Rollback on error
        await db.rollback()

        return {
            "service": "orders",
            "status": "failed",
            "records_cloned": 0,
            "duration_ms": int((datetime.now(timezone.utc) - start_time).total_seconds() * 1000),
            "error": str(e)
        }


@router.get("/clone/health")
async def clone_health_check(_: bool = Depends(verify_internal_api_key)):
    """
    Health check for internal cloning endpoint
    Used by orchestrator to verify service availability
    """
    return {
        "service": "orders",
        "clone_endpoint": "available",
        "version": "2.0.0"
    }


@router.delete("/tenant/{virtual_tenant_id}")
async def delete_demo_data(
    virtual_tenant_id: str,
    db: AsyncSession = Depends(get_db),
    _: bool = Depends(verify_internal_api_key)
):
    """Delete all order data for a virtual demo tenant"""
    logger.info("Deleting order data for virtual tenant", virtual_tenant_id=virtual_tenant_id)
    start_time = datetime.now(timezone.utc)

    try:
        virtual_uuid = uuid.UUID(virtual_tenant_id)

        # Count records
        order_count = await db.scalar(select(func.count(CustomerOrder.id)).where(CustomerOrder.tenant_id == virtual_uuid))
        item_count = await db.scalar(select(func.count(OrderItem.id)).where(OrderItem.tenant_id == virtual_uuid))
        customer_count = await db.scalar(select(func.count(Customer.id)).where(Customer.tenant_id == virtual_uuid))

        # Delete in order
        await db.execute(delete(OrderItem).where(OrderItem.tenant_id == virtual_uuid))
        await db.execute(delete(CustomerOrder).where(CustomerOrder.tenant_id == virtual_uuid))
        await db.execute(delete(Customer).where(Customer.tenant_id == virtual_uuid))
        await db.commit()

        duration_ms = int((datetime.now(timezone.utc) - start_time).total_seconds() * 1000)
        logger.info("Order data deleted successfully", virtual_tenant_id=virtual_tenant_id, duration_ms=duration_ms)

        return {
            "service": "orders",
            "status": "deleted",
            "virtual_tenant_id": virtual_tenant_id,
            "records_deleted": {
                "orders": order_count,
                "items": item_count,
                "customers": customer_count,
                "total": order_count + item_count + customer_count
            },
            "duration_ms": duration_ms
        }
    except Exception as e:
        logger.error("Failed to delete order data", error=str(e), exc_info=True)
        await db.rollback()
        raise HTTPException(status_code=500, detail=str(e))
