"""Prisca Content, SEO and Social worker. Provider-agnostic and safe-by-default.
Creates assets and a publishing calendar; it does not publish to external platforms.
"""
from datetime import datetime, timedelta
import re

PLATFORMS = {
    'instagram': ['reel','carousel','story','post'],
    'facebook': ['post','reel'],
    'youtube': ['short','video'],
    'pinterest': ['pin'],
    'google_business': ['post'],
    'website': ['blog','faq','internal_link_update']
}

class ContentWorker:
    def __init__(self, brand='Prisca Holidays'):
        self.brand=brand

    def keyword_plan(self, destination, theme=None):
        d=destination.strip()
        base=[f'{d} holiday package',f'{d} tour package',f'{d} travel package',f'{d} itinerary',f'best places to visit in {d}',f'best time to visit {d}']
        if theme: base += [f'{d} {theme.lower()}',f'{theme.lower()} package {d}']
        return {'destination':d,'primary':base[0],'secondary':base[1:],'clusters':[
            {'name':'commercial','keywords':base[:4]},
            {'name':'informational','keywords':base[4:]}
        ]}

    def create_assets(self, package, channels=None):
        channels=channels or list(PLATFORMS)
        name=package.get('name','').strip(); dest=package.get('destination','').strip(); theme=package.get('segment') or 'Travel'
        duration=package.get('package_duration','')
        seo=self.keyword_plan(dest,theme)
        assets=[]
        def add(platform,kind,title,body,cta=None):
            assets.append({'platform':platform,'type':kind,'title':title,'body':body,'cta':cta or 'Explore the package on Prisca Holidays.','status':'draft','publish_blocked':True})
        hook=f'{dest} in {duration}: a smarter way to plan your trip.'
        if 'instagram' in channels:
            add('instagram','reel',f'{dest} {theme} Reel',f'{hook} Show the strongest verified sights, route flow, stay style and one clear reason to book. Avoid unverified claims.','View the full itinerary on Prisca Holidays.')
            add('instagram','carousel',f'{dest} {theme}: {duration}',f'Slide 1: {name}. Slide 2: route. Slide 3: key experiences. Slide 4: inclusions. Slide 5: who it suits. Slide 6: CTA.', 'Save this itinerary and check the package details.')
            add('instagram','story',f'{dest} Travel Story',f'Poll: Planning {dest}? Follow-up frames: itinerary, travel tip, package CTA.')
        if 'facebook' in channels:
            add('facebook','post',f'{dest} Holiday Idea',f'Planning {dest}? Here is a {duration} option built around {theme.lower()}. The final post should use only verified itinerary, supplier and pricing data.','Message Prisca Holidays for availability.')
            add('facebook','reel',f'{dest} Travel Reel',f'{hook} Use destination visuals, concise captions and a direct enquiry CTA.')
        if 'youtube' in channels:
            add('youtube','short',f'{dest} in 30 Seconds',f'Hook: {hook} Then route, 3 verified highlights, who it is for, CTA.','See the complete itinerary on Prisca Holidays.')
            add('youtube','video',f'{dest} {duration} Guide',f'Explain route, day-wise plan, inclusions, exclusions, booking considerations and FAQs. Cite/verify changing facts before publication.')
        if 'pinterest' in channels:
            add('pinterest','pin',f'{dest} {duration} Itinerary',f'Pin copy targeting {seo["primary"]}: route, highlights and planning CTA.')
        if 'google_business' in channels:
            add('google_business','post',f'{dest} Travel Package',f'{duration} {dest} package idea for {theme.lower()}. Availability and pricing should be confirmed before posting.','Call or enquire with Prisca Holidays.')
        if 'website' in channels:
            add('website','blog',f'Complete {dest} Travel Guide',f'Create a pillar article covering when to go, route planning, major verified attractions, budgeting, FAQs and links to relevant Prisca packages. Primary keyword: {seo["primary"]}.','Explore Prisca Holidays packages.')
            add('website','faq',f'{dest} FAQ',f'Generate FAQ schema-ready questions from the approved package and verified destination research.','Read the package details.')
        return {'ok':True,'package':name,'destination':dest,'seo':seo,'assets':assets,'asset_count':len(assets),'publishing_blocked':True,'content_version':'v20'}

    def calendar(self, destination, start_date=None, days=7):
        start=datetime.fromisoformat(start_date) if start_date else datetime.now()
        slots=[]
        pattern=[('instagram','reel'),('facebook','post'),('website','blog'),('youtube','short'),('instagram','carousel'),('pinterest','pin'),('google_business','post')]
        for i in range(max(1,min(int(days),31))):
            platform,kind=pattern[i%len(pattern)]
            slots.append({'date':(start+timedelta(days=i)).date().isoformat(),'platform':platform,'type':kind,'destination':destination,'status':'planned','approval_required':True})
        return {'ok':True,'destination':destination,'days':len(slots),'slots':slots,'calendar_version':'v20'}
