"""
Management command: set_chat_system_prompt

Writes the optimised YOUR COMPANY AI system prompt to the master tenant's
chat_system_prompt field.

Usage:
    python manage.py set_chat_system_prompt
    python manage.py set_chat_system_prompt --tenant-id 2   # target a specific tenant
"""
from django.core.management.base import BaseCommand

SYSTEM_PROMPT = """You are the {company} AI assistant, answering visitors on the {company} website.

LIVE DATA: After this prompt you receive a second system message containing real-time data pulled from the database: products with prices and direct URLs, premium domain listings with URLs, FAQs, and contact/WhatsApp links. You must use this data to answer questions. Never guess prices or URLs.

LINKS: Always provide the exact URL from the injected data using markdown format [text](url). The chat renders these as clickable links. When listing products or domains, always include the link on the same line as the name and price. Example: "Web Starter Package - from £499 [View details](https://example.com/products/web-starter/)".

HUMAN AGENT REQUEST: If the visitor asks to speak to a person, an agent, or the team, respond with: "Of course! You can reach our team directly on WhatsApp: [Chat with us](<whatsapp_url>)" -- replacing <whatsapp_url> with the WhatsApp link from the injected CONTACT data. Keep it short.

TONE: Warm, direct, no filler. Short replies (under 100 words) unless asked for detail. Never use em dashes. Use plain sentences, not bullet points for short answers. For listing products or domains, a short list is fine.

WHAT YOU CANNOT DO: Process payments, access accounts, or promise specific delivery dates."""


def _prompt_for(tenant=None):
    """The prompt with this install's name written in.

    The name used to be a literal, so a copy of this file told a client's
    visitors they were talking to somebody else's assistant."""
    from apps.pages.branding import company_name
    return SYSTEM_PROMPT.replace('{company}', company_name(tenant) or 'this site')


class Command(BaseCommand):
    help = 'Write the optimised YOUR COMPANY AI system prompt to the master tenant'

    def add_arguments(self, parser):
        parser.add_argument(
            '--tenant-id', type=int, default=None,
            help='Target a specific tenant by PK (default: master tenant)'
        )
        parser.add_argument(
            '--dry-run', action='store_true',
            help='Print the prompt without saving'
        )

    def handle(self, *args, **options):
        if options['dry_run']:
            self.stdout.write(_prompt_for(tenant))
            return

        from apps.tenants.models import Tenant
        if options['tenant_id']:
            try:
                tenant = Tenant.objects.get(pk=options['tenant_id'])
            except Tenant.DoesNotExist:
                self.stderr.write(self.style.ERROR(f"No tenant with pk={options['tenant_id']}"))
                return
        else:
            tenant = Tenant.objects.filter(is_master=True).first()
            if not tenant:
                tenant = Tenant.objects.first()
            if not tenant:
                self.stderr.write(self.style.ERROR('No tenants found in DB'))
                return

        tenant.chat_system_prompt = _prompt_for(tenant)
        tenant.save(update_fields=['chat_system_prompt'])
        self.stdout.write(self.style.SUCCESS(
            f'System prompt updated for tenant: {tenant.name} (pk={tenant.pk})'
        ))
