#!/usr/bin/env python3
"""
Social Post Generator — ReceptionistAI / AgileAdapt
Generates platform-optimised posts using OpenRouter AI.

Platforms:
  - Facebook:       150-200 words, story format, CTA
  - LinkedIn:       Professional, 300 words, thought leadership
  - Instagram:      Visual description + caption + 5 hashtags
  - Google Business: 150 words, local SEO keywords

Usage:
  python social_post_generator.py --platform facebook --topic "missed calls" --brand receptionistai
  python social_post_generator.py --platform linkedin --topic "ROI of AI receptionist" --brand agileadapt
  python social_post_generator.py --batch --count 10 --platform facebook --brand receptionistai

Output:
  E:/genesis-system/AGILEADAPT/marketing/posts/generated/
"""

import os
import sys
import json
import argparse
import time
from datetime import datetime
from pathlib import Path

import requests

# ─── Configuration ────────────────────────────────────────────────────────────

OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "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")
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
MODEL = "anthropic/claude-3-haiku"  # Fast, cheap, quality output

OUTPUT_DIR = Path("E:/genesis-system/AGILEADAPT/marketing/posts/generated")

# ─── Brand Context ─────────────────────────────────────────────────────────────

BRAND_CONTEXT = {
    "receptionistai": {
        "name": "ReceptionistAI",
        "tagline": "Never miss a call. Never lose a lead.",
        "url": "receptionistai.com.au",
        "pricing": "$497/month — setup fee waived for launch clients",
        "target": "Australian tradies, small business owners, service businesses",
        "pain_point": "Missed calls = lost revenue. 67% of small business calls go unanswered.",
        "tone": "Warm, direct, results-focused. Professional Australian voice. No slang.",
        "key_stats": [
            "67% of small business calls go unanswered",
            "Average missed call costs $60-$200 in lost revenue",
            "10 missed calls/day = $16,800/month in lost revenue",
            "Setup in 48 hours. Australian voice. 24/7 availability.",
        ],
        "ctas": [
            "Book a free 15-minute demo at receptionistai.com.au",
            "See what missed calls are costing you — receptionistai.com.au",
            "Setup fee waived this month — claim your spot at receptionistai.com.au",
            "Listen to a real call recording at receptionistai.com.au",
        ],
        "banned_words": ["G'day", "mate", "too easy", "righto", "sweet as", "no worries mate"],
    },
    "agileadapt": {
        "name": "AgileAdapt",
        "tagline": "The Automation Architects.",
        "url": "agileadapt.com.au",
        "pricing": "Custom — contact for agency pricing",
        "target": "Agency owners, operations managers, business owners scaling with AI",
        "pain_point": "Manual processes are the bottleneck. Every hour spent on admin is an hour not spent on revenue.",
        "tone": "Cutting-edge, credible, results-driven. Engineering-level precision. Never marketing-bro.",
        "key_stats": [
            "AI receptionists handle 300-1,200 calls/month from $497",
            "85-89% profit margin on each AI deployment",
            "Setup time: 48 hours from contract to live calls",
            "30% recurring commission for agency partners",
        ],
        "ctas": [
            "Partner with us — 30% recurring commission. agileadapt.com.au",
            "See the full stack at agileadapt.com.au",
            "Book a technical demo — agileadapt.com.au",
        ],
        "banned_words": ["manual", "traditional", "slow", "admin", "G'day", "mate"],
    },
}

# ─── Platform Specifications ───────────────────────────────────────────────────

PLATFORM_SPECS = {
    "facebook": {
        "word_count": "150-200 words",
        "format": "story format — open with a hook (scenario or stat), build tension, resolve with the solution, end with a clear CTA",
        "tone_note": "conversational but professional, no emojis in body text, 1-2 line breaks between paragraphs",
        "cta_placement": "final paragraph",
        "hashtag_count": 3,
        "hashtags": "#AIReceptionist #SmallBusinessAustralia #ReceptionistAI",
    },
    "linkedin": {
        "word_count": "250-320 words",
        "format": "thought leadership — open with a bold statement or surprising stat, develop the idea with data/logic, provide practical insight, end with a question or CTA",
        "tone_note": "professional, intelligent, data-backed. No fluff. Speak to business owners and operators.",
        "cta_placement": "final 2 lines",
        "hashtag_count": 4,
        "hashtags": "#VoiceAI #BusinessAutomation #AustralianBusiness #AIStrategy",
    },
    "instagram": {
        "word_count": "80-120 words for caption",
        "format": "visual-first — first line is the hook (single punchy sentence), body is supporting story or stat, end with CTA. Also provide a 1-sentence visual description for the graphic.",
        "tone_note": "punchy, visual-thinking, slightly more informal than Facebook but still professional",
        "cta_placement": "last line before hashtags",
        "hashtag_count": 8,
        "hashtags": "#AIReceptionist #ReceptionistAI #AustralianBusiness #TradiesAustralia #NeverMissACall #SmallBusinessAustralia #VoiceAI #BusinessAutomation",
    },
    "google_business": {
        "word_count": "130-160 words",
        "format": "local SEO-optimised — include city name naturally, focus on specific business type (tradies, plumbers, electricians etc), include pricing or offer if relevant, end with CTA",
        "tone_note": "informative, trustworthy, locally relevant. Write as if answering 'why should I use this service in [city]'",
        "cta_placement": "final line",
        "hashtag_count": 0,
        "hashtags": "",
    },
}

# ─── Prompt Builder ────────────────────────────────────────────────────────────

def build_prompt(platform: str, topic: str, brand: str, extra_context: str = "") -> str:
    brand_data = BRAND_CONTEXT[brand]
    platform_data = PLATFORM_SPECS[platform]

    banned = ", ".join(f'"{w}"' for w in brand_data["banned_words"])
    stats = "\n".join(f"- {s}" for s in brand_data["key_stats"])
    cta_example = brand_data["ctas"][0]

    prompt = f"""You are a content marketing specialist for {brand_data['name']}, an Australian AI technology company.

BRAND BRIEF:
- Name: {brand_data['name']}
- Tagline: {brand_data['tagline']}
- Target audience: {brand_data['target']}
- Core pain point: {brand_data['pain_point']}
- Tone: {brand_data['tone']}
- Website: {brand_data['url']}
- Pricing: {brand_data['pricing']}

KEY FACTS TO USE (use selectively, not all):
{stats}

BANNED WORDS (never use these): {banned}

PLATFORM: {platform.upper()}
POST SPECIFICATIONS:
- Length: {platform_data['word_count']}
- Format: {platform_data['format']}
- Tone note: {platform_data['tone_note']}
- CTA placement: {platform_data['cta_placement']}
- Hashtags: Include {platform_data['hashtag_count']} relevant hashtags at the end
- Example CTA: {cta_example}

TOPIC FOR THIS POST: {topic}
{f"ADDITIONAL CONTEXT: {extra_context}" if extra_context else ""}

IMPORTANT RULES:
1. Write for real Australian business owners — they are busy, practical, results-focused
2. Never use clichéd Australian slang — professional does not mean formal
3. Every post must make the reader feel understood before it sells anything
4. Use specific numbers where possible (from the key facts above)
5. The CTA must be specific and action-oriented, not vague ("Learn more" is banned)
6. No emojis in the body text (hashtags section can have 1-2 relevant ones if platform allows)

Write the complete, ready-to-post content now. Output ONLY the post text — no commentary, no labels, no explanations."""

    return prompt

# ─── API Call ─────────────────────────────────────────────────────────────────

def generate_post(platform: str, topic: str, brand: str, extra_context: str = "") -> dict:
    """Generate a single platform-optimised post."""
    prompt = build_prompt(platform, topic, brand, extra_context)

    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://agileadapt.com.au",
        "X-Title": "ReceptionistAI Content Generator",
    }

    payload = {
        "model": MODEL,
        "messages": [
            {
                "role": "system",
                "content": "You are an expert content marketer specialising in Australian B2B and B2C marketing for AI and technology companies. You write copy that converts because it speaks directly to the reader's real problems.",
            },
            {"role": "user", "content": prompt},
        ],
        "temperature": 0.75,
        "max_tokens": 800,
    }

    start = time.time()
    try:
        response = requests.post(OPENROUTER_URL, headers=headers, json=payload, timeout=30)
        elapsed = int((time.time() - start) * 1000)

        if response.status_code != 200:
            return {
                "status": "error",
                "error": f"HTTP {response.status_code}: {response.text[:200]}",
                "elapsed_ms": elapsed,
            }

        data = response.json()
        content = data["choices"][0]["message"]["content"].strip()
        usage = data.get("usage", {})

        return {
            "status": "success",
            "platform": platform,
            "brand": brand,
            "topic": topic,
            "content": content,
            "generated_at": datetime.now().isoformat(),
            "model": MODEL,
            "tokens": usage.get("total_tokens", 0),
            "elapsed_ms": elapsed,
        }

    except requests.exceptions.Timeout:
        return {"status": "error", "error": "Request timed out after 30s", "elapsed_ms": 30000}
    except Exception as e:
        return {"status": "error", "error": str(e), "elapsed_ms": int((time.time() - start) * 1000)}

# ─── Batch Generator ──────────────────────────────────────────────────────────

BATCH_TOPICS = {
    "receptionistai": {
        "facebook": [
            "A customer called at 11pm — here's what happened",
            "Your receptionist doesn't work 24/7. Ours does.",
            "George's plumbing business got 3 new jobs while he slept",
            "What does the AI actually say when someone calls?",
            "The missed call problem: how much is it costing Australian tradies?",
            "Why 67% of small business calls go unanswered",
            "3 months, 0 missed calls — the ReceptionistAI story",
            "Setup in 48 hours — here's exactly how it works",
            "The after-hours revenue gap hiding in your phone system",
            "Your competitors are already answering after hours. Are you?",
        ],
        "google_business": [
            "AI receptionist for plumbers Melbourne",
            "Never miss a call — small business AI answering service Sydney",
            "24/7 automated receptionist for tradies Brisbane",
            "AI phone answering for electricians Perth",
            "Automated booking and call handling for small business Australia",
        ],
    },
    "agileadapt": {
        "linkedin": [
            "The receptionist bottleneck: why voice AI is the fastest ROI in 2026",
            "Under the hood: how we built a 24/7 AI receptionist for Australian tradies",
            "Why we chose Telnyx over Twilio for voice AI infrastructure",
            "The $16,800/month problem hiding in plain sight for small businesses",
            "Voice AI benchmarks: latency, accuracy, and caller satisfaction scores",
            "How to pitch AI voice agents to your clients — a framework that works",
            "The after-hours revenue gap: data from 100 AI receptionist deployments",
            "Why locally-tuned voice AI outperforms global solutions in Australia",
            "Prompt engineering for voice AI — what 6 months of iteration taught us",
            "Agency partners: 30% recurring commission on every AI deployment",
        ],
    },
}

def run_batch(brand: str, platform: str, count: int = None):
    """Run batch generation for a brand/platform combination."""
    topics = BATCH_TOPICS.get(brand, {}).get(platform, [])
    if not topics:
        print(f"No batch topics configured for {brand}/{platform}")
        return []

    if count:
        topics = topics[:count]

    print(f"Generating {len(topics)} {platform} posts for {brand}...")
    results = []

    for i, topic in enumerate(topics, 1):
        print(f"  [{i}/{len(topics)}] {topic[:60]}...")
        result = generate_post(platform, topic, brand)

        if result["status"] == "success":
            print(f"    OK ({result['elapsed_ms']}ms, {result['tokens']} tokens)")
        else:
            print(f"    FAILED: {result.get('error', 'unknown')}")

        results.append(result)
        time.sleep(0.5)  # Rate limiting courtesy pause

    return results

# ─── Save Output ──────────────────────────────────────────────────────────────

def save_post(result: dict, output_dir: Path = OUTPUT_DIR):
    """Save a generated post to file."""
    output_dir.mkdir(parents=True, exist_ok=True)

    if result["status"] != "success":
        return

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    platform = result.get("platform", "unknown")
    brand = result.get("brand", "unknown")
    filename = f"{brand}_{platform}_{timestamp}.md"
    filepath = output_dir / filename

    content = f"""# Generated Post
**Platform:** {platform.title()}
**Brand:** {result.get('brand', '').title()}
**Topic:** {result.get('topic', '')}
**Generated:** {result.get('generated_at', '')}
**Model:** {result.get('model', '')}
**Tokens:** {result.get('tokens', 0)}

---

{result['content']}
"""

    filepath.write_text(content, encoding="utf-8")
    print(f"    Saved: {filepath.name}")
    return filepath

# ─── Log to JSON ──────────────────────────────────────────────────────────────

def log_results(results: list, output_dir: Path = OUTPUT_DIR):
    """Log all results to a JSONL file for PostgreSQL ingestion."""
    output_dir.mkdir(parents=True, exist_ok=True)
    log_file = output_dir / "generation_log.jsonl"

    with open(log_file, "a", encoding="utf-8") as f:
        for r in results:
            f.write(json.dumps(r) + "\n")

    print(f"\nResults logged to {log_file}")

# ─── Main ─────────────────────────────────────────────────────────────────────

def main():
    parser = argparse.ArgumentParser(
        description="Generate platform-optimised social media posts for ReceptionistAI / AgileAdapt"
    )
    parser.add_argument("--platform", choices=["facebook", "linkedin", "instagram", "google_business"], required=False)
    parser.add_argument("--topic", type=str, help="Topic for the post")
    parser.add_argument("--brand", choices=["receptionistai", "agileadapt"], default="receptionistai")
    parser.add_argument("--extra-context", type=str, default="", help="Additional context for the AI")
    parser.add_argument("--batch", action="store_true", help="Run batch generation from pre-defined topics")
    parser.add_argument("--count", type=int, help="Number of posts in batch mode")
    parser.add_argument("--save", action="store_true", default=True, help="Save output to files")
    parser.add_argument("--print", action="store_true", help="Print generated content to stdout")

    args = parser.parse_args()

    if args.batch:
        # Batch mode
        if not args.platform:
            print("Error: --platform required for batch mode")
            sys.exit(1)

        results = run_batch(args.brand, args.platform, args.count)

        if args.save:
            for r in results:
                save_post(r)
            log_results(results)

        successes = sum(1 for r in results if r["status"] == "success")
        print(f"\nBatch complete: {successes}/{len(results)} succeeded")

    elif args.topic and args.platform:
        # Single post mode
        print(f"Generating {args.platform} post for {args.brand}...")
        result = generate_post(args.platform, args.topic, args.brand, args.extra_context)

        if result["status"] == "success":
            print(f"\nPost generated ({result['elapsed_ms']}ms, {result['tokens']} tokens)\n")
            print("=" * 60)
            print(result["content"])
            print("=" * 60)

            if args.save:
                save_post(result)
                log_results([result])
        else:
            print(f"Error: {result.get('error', 'Unknown error')}")
            sys.exit(1)

    else:
        parser.print_help()
        print("\nExamples:")
        print('  python social_post_generator.py --platform facebook --topic "missed calls" --brand receptionistai')
        print('  python social_post_generator.py --batch --platform linkedin --brand agileadapt --count 5')


if __name__ == "__main__":
    main()
