"""
AI Content Rewriter
Rewrites competitor content snippets into unique, SEO-optimized text
Uses Claude AI to maintain keywords while creating original content
"""

import json
import os
from datetime import datetime
from anthropic import Anthropic


class AIContentRewriter:
    def __init__(self):
        """Initialize AI content rewriter"""
        # Check for API key
        self.api_key = os.getenv('ANTHROPIC_API_KEY')
        if not self.api_key:
            print("\n" + "="*60)
            print("ANTHROPIC API KEY REQUIRED")
            print("="*60)
            print("\nTo use the AI rewriter, you need an Anthropic API key.")
            print("\nSteps:")
            print("1. Go to: https://console.anthropic.com/")
            print("2. Sign up or log in")
            print("3. Go to API Keys section")
            print("4. Create a new API key")
            print("5. Set environment variable:")
            print("   Windows: setx ANTHROPIC_API_KEY \"your-key-here\"")
            print("   Or add to .env file")
            print("\n" + "="*60)
            raise ValueError("ANTHROPIC_API_KEY not found in environment")
        
        self.client = Anthropic(api_key=self.api_key)
        
        # Load keywords
        try:
            with open('reports/competitor_keywords.json', 'r') as f:
                keyword_data = json.load(f)
                self.keywords = [kw['keyword'] for kw in keyword_data['keywords'][:50]]
        except:
            print("[WARNING] No keywords found. Using default conservatory keywords.")
            self.keywords = [
                'conservatory roof', 'roof replacement', 'tiled conservatory',
                'conservatory roof replacement', 'building regulations'
            ]
        
        # Load content snippets
        try:
            with open('reports/content_snippets.json', 'r') as f:
                self.content_data = json.load(f)
        except:
            print("[ERROR] No content_snippets.json found. Run extract_content_snippets.py first.")
            self.content_data = None
    
    def rewrite_all_content(self, max_paragraphs=50):
        """
        Rewrite all extracted content snippets
        """
        if not self.content_data:
            return None
        
        print("\n" + "="*60)
        print("AI CONTENT REWRITER")
        print("="*60)
        print(f"\nRewriting up to {max_paragraphs} paragraphs...")
        print(f"Target keywords: {len(self.keywords)}")
        
        rewritten_content = []
        paragraph_count = 0
        
        for site in self.content_data['content']:
            print(f"\n[SITE] {site['title']}")
            
            site_rewritten = {
                'original_url': site['url'],
                'original_title': site['title'],
                'sections': []
            }
            
            for section in site['sections']:
                if paragraph_count >= max_paragraphs:
                    break
                
                print(f"  [SECTION] {section['heading']}")
                
                section_rewritten = {
                    'heading': section['heading'],
                    'paragraphs': []
                }
                
                for para in section['paragraphs']:
                    if paragraph_count >= max_paragraphs:
                        break
                    
                    # Skip very short paragraphs
                    if para['word_count'] < 30:
                        continue
                    
                    # Rewrite paragraph
                    print(f"    Rewriting paragraph {paragraph_count + 1}/{max_paragraphs}...")
                    
                    rewritten = self.rewrite_paragraph(
                        para['text'],
                        para.get('has_keywords', [])
                    )
                    
                    if rewritten:
                        section_rewritten['paragraphs'].append({
                            'original': para['text'],
                            'rewritten': rewritten,
                            'original_word_count': para['word_count'],
                            'rewritten_word_count': len(rewritten.split()),
                            'keywords_used': para.get('has_keywords', [])
                        })
                        
                        paragraph_count += 1
                
                if section_rewritten['paragraphs']:
                    site_rewritten['sections'].append(section_rewritten)
            
            if site_rewritten['sections']:
                rewritten_content.append(site_rewritten)
        
        # Export results
        self.export_rewritten_content(rewritten_content)
        
        return rewritten_content
    
    def rewrite_paragraph(self, original_text, keywords_in_text):
        """
        Rewrite a single paragraph using Claude AI
        """
        # Build keyword list for this paragraph
        relevant_keywords = keywords_in_text if keywords_in_text else self.keywords[:10]
        
        prompt = f"""You are an expert SEO content writer for a conservatory business.

Rewrite the following text to be:
1. Completely unique and original (no plagiarism)
2. SEO-optimized with natural keyword integration
3. Professional and engaging
4. Similar length to the original
5. UK English spelling and grammar

IMPORTANT KEYWORDS TO INCLUDE (use naturally):
{', '.join(relevant_keywords)}

ORIGINAL TEXT:
{original_text}

INSTRUCTIONS:
- Rewrite in your own words while keeping the same information
- Naturally incorporate the keywords listed above
- Maintain a professional, helpful tone
- Keep similar length to original
- Use UK English (e.g., "colour" not "color")
- Make it engaging and easy to read

REWRITTEN TEXT:"""

        try:
            message = self.client.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=1024,
                messages=[
                    {"role": "user", "content": prompt}
                ]
            )
            
            rewritten = message.content[0].text.strip()
            return rewritten
        
        except Exception as e:
            print(f"      [ERROR] AI rewrite failed: {e}")
            return None
    
    def export_rewritten_content(self, rewritten_content):
        """
        Export rewritten content to HTML and JSON
        """
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        
        # Export JSON (timestamped and static)
        json_path_ts = f"reports/rewritten_content_{timestamp}.json"
        json_path_static = "reports/rewritten_content.json"
        
        json_data = {
            'rewrite_date': datetime.now().isoformat(),
            'total_paragraphs': sum(len(s['paragraphs']) for site in rewritten_content for s in site['sections']),
            'keywords_used': self.keywords,
            'content': rewritten_content
        }
        
        with open(json_path_ts, 'w', encoding='utf-8') as f:
            json.dump(json_data, f, indent=2)
        with open(json_path_static, 'w', encoding='utf-8') as f:
            json.dump(json_data, f, indent=2)
        
        print(f"\n[OK] Saved JSON: {json_path_ts}")
        print(f"[OK] Saved JSON: {json_path_static}")
        
        # Export HTML (timestamped and static)
        html_path_ts = f"reports/rewritten_content_{timestamp}.html"
        html_path_static = "reports/rewritten_content.html"
        
        self.generate_rewritten_html(rewritten_content, html_path_ts)
        self.generate_rewritten_html(rewritten_content, html_path_static)
        
        print(f"[OK] Saved HTML: {html_path_ts}")
        print(f"[OK] Saved HTML: {html_path_static}")
        
        print(f"\n{'='*60}")
        print("[OK] CONTENT REWRITING COMPLETE!")
        print(f"{'='*60}")
        print(f"\nRewritten {sum(len(s['paragraphs']) for site in rewritten_content for s in site['sections'])} paragraphs")
        print(f"Ready to use for your website!")
    
    def generate_rewritten_html(self, rewritten_content, output_path):
        """
        Generate HTML comparison report
        """
        total_paragraphs = sum(len(s['paragraphs']) for site in rewritten_content for s in site['sections'])
        
        html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <title>AI Rewritten Content - Ready for Your Website</title>
            <style>
                body {{ font-family: 'Segoe UI', Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }}
                .container {{ max-width: 1600px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
                h1 {{ color: #2c3e50; border-bottom: 3px solid #27ae60; padding-bottom: 10px; }}
                h2 {{ color: #34495e; margin-top: 40px; background: #ecf0f1; padding: 15px; border-left: 4px solid #27ae60; }}
                h3 {{ color: #7f8c8d; margin-top: 30px; }}
                .summary {{ display: flex; justify-content: space-around; margin: 30px 0; }}
                .metric {{ text-align: center; padding: 20px; background: #d5f4e6; border-radius: 8px; }}
                .metric-value {{ font-size: 36px; font-weight: bold; color: #27ae60; }}
                .metric-label {{ color: #7f8c8d; margin-top: 5px; }}
                .comparison {{ display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 20px 0; }}
                .original {{ background: #fff3cd; padding: 20px; border-radius: 8px; border-left: 4px solid #f39c12; }}
                .rewritten {{ background: #d5f4e6; padding: 20px; border-radius: 8px; border-left: 4px solid #27ae60; }}
                .label {{ font-weight: bold; color: #7f8c8d; margin-bottom: 10px; text-transform: uppercase; font-size: 12px; }}
                .text {{ line-height: 1.8; }}
                .stats {{ color: #7f8c8d; font-size: 12px; margin-top: 10px; }}
                .copy-btn {{ background: #27ae60; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; margin-top: 10px; font-weight: bold; }}
                .copy-btn:hover {{ background: #229954; }}
                .keywords {{ background: #fff; padding: 15px; margin: 20px 0; border-radius: 5px; border: 1px solid #ddd; }}
                .keyword-tag {{ display: inline-block; background: #3498db; color: white; padding: 5px 10px; border-radius: 3px; margin: 3px; font-size: 12px; }}
                .instructions {{ background: #d5f4e6; border-left: 4px solid #27ae60; padding: 20px; margin: 20px 0; }}
                .section-box {{ background: #f9f9f9; padding: 20px; margin: 20px 0; border-radius: 8px; }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1>✨ AI Rewritten Content - SEO Optimized & Ready to Use</h1>
                <p><strong>Generated:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
                
                <div class="instructions">
                    <h3>✅ This Content is Ready for Your Website!</h3>
                    <ul>
                        <li><strong>100% Unique</strong> - Completely rewritten by AI, no plagiarism</li>
                        <li><strong>SEO Optimized</strong> - Keywords naturally integrated</li>
                        <li><strong>Professional Tone</strong> - Written for UK conservatory customers</li>
                        <li><strong>Click "Copy Rewritten Text"</strong> to use on your website</li>
                        <li><strong>Compare with original</strong> to see the improvements</li>
                    </ul>
                </div>
                
                <div class="summary">
                    <div class="metric">
                        <div class="metric-value">{total_paragraphs}</div>
                        <div class="metric-label">Paragraphs Rewritten</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">{len(self.keywords)}</div>
                        <div class="metric-label">Keywords Optimized</div>
                    </div>
                    <div class="metric">
                        <div class="metric-value">{len(rewritten_content)}</div>
                        <div class="metric-label">Source Sites</div>
                    </div>
                </div>
                
                <div class="keywords">
                    <strong>Target Keywords:</strong><br>
        """
        
        for keyword in self.keywords[:20]:
            html += f'<span class="keyword-tag">{keyword}</span>'
        
        html += '</div>'
        
        # Add rewritten content
        for site in rewritten_content:
            html += f"""
                <h2>📄 Content from: {site['original_title']}</h2>
                <p style="color: #7f8c8d; font-size: 14px;">Original source: {site['original_url']}</p>
            """
            
            for section in site['sections']:
                html += f"""
                    <div class="section-box">
                        <h3>📌 {section['heading']}</h3>
                """
                
                for i, para in enumerate(section['paragraphs'], 1):
                    html += f"""
                        <div class="comparison">
                            <div class="original">
                                <div class="label">Original (Competitor)</div>
                                <div class="text">{para['original']}</div>
                                <div class="stats">{para['original_word_count']} words</div>
                            </div>
                            <div class="rewritten">
                                <div class="label">✨ AI Rewritten (Use This!)</div>
                                <div class="text">{para['rewritten']}</div>
                                <div class="stats">{para['rewritten_word_count']} words | Keywords: {', '.join(para['keywords_used'][:3])}</div>
                                <button class="copy-btn" onclick="copyText(this)">Copy Rewritten Text</button>
                                <textarea style="display:none;">{para['rewritten']}</textarea>
                            </div>
                        </div>
                    """
                
                html += '</div>'  # Close section-box
        
        html += """
                <script>
                    function copyText(button) {
                        const textarea = button.nextElementSibling;
                        textarea.style.display = 'block';
                        textarea.select();
                        document.execCommand('copy');
                        textarea.style.display = 'none';
                        
                        button.textContent = '✓ Copied!';
                        button.style.background = '#229954';
                        setTimeout(() => {
                            button.textContent = 'Copy Rewritten Text';
                            button.style.background = '#27ae60';
                        }, 2000);
                    }
                </script>
            </div>
        </body>
        </html>
        """
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html)


if __name__ == "__main__":
    try:
        rewriter = AIContentRewriter()
        
        print("\nHow many paragraphs would you like to rewrite?")
        print("(Each paragraph costs ~$0.01-0.02 in API credits)")
        print("\nRecommended: 20-50 for a good content library")
        
        try:
            max_para = int(input("\nEnter number (default 30): ") or "30")
        except:
            max_para = 30
        
        content = rewriter.rewrite_all_content(max_paragraphs=max_para)
        
        print("\n[SUCCESS] Open reports/rewritten_content.html to see your new content!")
        print("\nYou can now copy and paste this content directly to your website.")
        print("It's 100% unique, SEO-optimized, and ready to use!")
    
    except ValueError as e:
        print(f"\n{e}")
        print("\nSetup instructions above. Run again after setting API key.")
    except Exception as e:
        print(f"\n[ERROR] {e}")
