import json
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, current_app
from flask_login import login_required, current_user
from app.extensions import db, csrf
from app.ai.diamond import run_sync
from app.models.report import Report

intelligence_bp = Blueprint("intelligence", __name__, url_prefix="/intelligence")


@intelligence_bp.route("/competitors/<int:report_id>")
@login_required
def competitors(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return redirect(url_for("dashboard.index"))
    return render_template("intelligence/competitors.html", report=report)


@intelligence_bp.route("/api/wizard-questions/<int:report_id>", methods=["POST"])
@csrf.exempt
@login_required
def api_wizard_questions(report_id):
    """AI generates smart questions based on the project to help find competitors."""
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    try:
        from app.ai.diamond import call_ai, _parse_json
        from app.ai.providers import call_ai_for_screen

        lang = "Arabic" if report.language == "ar" else "English"
        messages = [
            {"role": "system", "content": (
                f"You are a competitive intelligence expert. Based on the project details below, "
                f"generate 4-6 smart questions to ask the user that will help you identify and analyze their competitors. "
                f"Questions should cover: target market/country, industry segment, direct vs indirect competitors, "
                f"pricing range, company size, and any known competitor names.\n"
                f"Return JSON: {{\"questions\": [{{\"id\": \"q1\", \"question\": \"...\", \"type\": \"text|select|multi\", \"options\": [\"...\"]}}]}}\n"
                f"For select/multi types, provide relevant options. Language: {lang}"
            )},
            {"role": "user", "content": (
                f"Project: {report.project_name}\n"
                f"Description: {report.project_description}\n"
                f"Generate questions to help identify competitors."
            )},
        ]

        response = run_sync(call_ai_for_screen(messages, "competitor_analysis"))
        questions = _parse_json(response)
        return jsonify({"status": "done", "data": questions})
    except Exception as e:
        current_app.logger.error(f"Wizard questions failed: {e}")
        return jsonify({"error": str(e)}), 500


@intelligence_bp.route("/api/analyze-competitors/<int:report_id>", methods=["POST"])
@csrf.exempt
@login_required
def api_analyze(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        return jsonify({"error": "Unauthorized"}), 403

    data = request.get_json(silent=True) or {}
    competitor_urls = data.get("urls", [])
    wizard_answers = data.get("answers", {})

    try:
        from app.ai.prompts.competitor import get_competitor_prompt
        from app.ai.diamond import call_ai, _parse_json
        from app.ai.providers import call_ai_for_screen

        scraped_data = []
        if competitor_urls:
            import aiohttp
            async def scrape_competitors():
                results = []
                async with aiohttp.ClientSession() as session:
                    for url in competitor_urls[:5]:
                        try:
                            async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as resp:
                                text = await resp.text()
                                import re
                                title = re.search(r'<title>(.*?)</title>', text, re.I)
                                desc = re.search(r'<meta[^>]*name=["\']description["\'][^>]*content=["\'](.*?)["\']', text, re.I)
                                results.append({
                                    "url": url,
                                    "name": title.group(1) if title else url,
                                    "description": desc.group(1) if desc else "",
                                })
                        except Exception:
                            results.append({"url": url, "name": url, "description": ""})
                return results
            scraped_data = run_sync(scrape_competitors())

        answers_text = ""
        if wizard_answers:
            for qid, answer in wizard_answers.items():
                if isinstance(answer, list):
                    answer = ", ".join(answer)
                answers_text += f"- {qid}: {answer}\n"

        lang = "Arabic" if report.language == "ar" else "English"
        messages = [
            {"role": "system", "content": (
                "You are a competitive intelligence analyst. Based on the project info, "
                "user answers about their market, and any scraped competitor data, "
                "perform a comprehensive competitor analysis.\n\n"
                f"Language: {lang}\n\n"
                "Return JSON with keys:\n"
                "competitors: [{name, website, strengths: [], weaknesses: [], market_position, pricing, threat_level}],\n"
                "competitive_advantages: [],\n"
                "market_gaps: [],\n"
                "recommended_differentiation: string,\n"
                "overall_threat_level: string (low/medium/high),\n"
                "strategic_recommendations: []"
            )},
            {"role": "user", "content": (
                f"Project: {report.project_name}\n"
                f"Description: {report.project_description}\n\n"
                f"User's market context:\n{answers_text}\n\n"
                f"Scraped competitor data:\n{json.dumps(scraped_data, ensure_ascii=False) if scraped_data else 'No URLs provided - research competitors based on the answers above.'}\n\n"
                "Analyze competitors thoroughly. If no URLs were given, identify likely competitors based on the market context."
            )},
        ]

        response = run_sync(call_ai_for_screen(messages, "competitor_analysis"))
        analysis = _parse_json(response)
        return jsonify({"status": "done", "analysis": analysis, "scraped": scraped_data})
    except Exception as e:
        current_app.logger.error(f"Competitor analysis failed: {e}")
        return jsonify({"error": str(e)}), 500
