from sqlalchemy.orm import Session
from sqlalchemy.orm.attributes import flag_modified

from app.core.config import get_settings
from app.core.security import hash_password
from app.models import JobSource, Plan, Profile, Subscription, User
from app.services.entitlements import DEFAULT_ENTITLEMENTS, assign_plan
from app.services.portal_catalog import all_portal_definitions

DEFAULT_PLANS = [
    {
        "key": "free",
        "name": "Gratis",
        "description": "Empieza hoy: busca ofertas y prueba la IA en tu currículum. Sin tarjeta.",
        "price_cents": 0,
        "currency": "EUR",
        "interval": "month",
        "sort_order": 0,
        "features": [
            "Ofertas ordenadas para ti",
            "Ventana de oro: ves si salió hace menos de 24 h",
            "Hasta 15 portales de empleo (España)",
            "1 currículum (pegar texto o subir PDF)",
            "3 mejoras o adaptaciones con IA al mes",
            "Hasta 20 candidaturas en seguimiento",
        ],
        "entitlements": DEFAULT_ENTITLEMENTS["free"],
    },
    {
        "key": "esencial",
        "name": "Esencial",
        "description": "7,90 €: búsqueda seria en España + 3 currículums y 20 mejoras con IA al mes.",
        "price_cents": 790,
        "currency": "EUR",
        "interval": "month",
        "sort_order": 1,
        "features": [
            "Más portales de empleo en España",
            "El mismo anuncio en varios portales (no aplicas dos veces)",
            "3 currículums (crear, subir PDF o sustituir)",
            "20 mejoras o adaptaciones con IA al mes",
            "Candidaturas ilimitadas",
            "Avisos de ofertas nuevas",
        ],
        "entitlements": DEFAULT_ENTITLEMENTS["esencial"],
    },
    {
        "key": "profesional",
        "name": "Profesional",
        "description": "14,90 €: IA de CV + detector de ofertas fantasma + qué decir cuando no contestan.",
        "price_cents": 1490,
        "currency": "EUR",
        "interval": "month",
        "sort_order": 2,
        "features": [
            "Portales de España e internacionales",
            "Detector de ofertas fantasma (único en el mercado)",
            "Poder de compra real: 38k en Valencia ≠ 38k en Madrid",
            "Anti-silencio: el día y el texto del seguimiento",
            "10 currículums y 100 mejoras con IA al mes",
            "Ayuda para rellenar el envío a la oferta",
            "Simulador de entrevista",
        ],
        "entitlements": DEFAULT_ENTITLEMENTS["profesional"],
    },
    {
        "key": "carrera_max",
        "name": "Carrera Max",
        "description": "24,90 €: sin techo. El mismo plan que usa el administrador de JobsWorld.",
        "price_cents": 2490,
        "currency": "EUR",
        "interval": "month",
        "sort_order": 3,
        "features": [
            "Todo lo de Profesional, sin techos",
            "Calendario .ics de seguimientos (entra en tu móvil)",
            "Currículums e IA ilimitados",
            "Preparar y lanzar el envío a la oferta",
            "Todos los portales de empleo",
            "El mismo plan que usa el administrador",
        ],
        "entitlements": DEFAULT_ENTITLEMENTS["carrera_max"],
    },
]

# Skills genéricas de ejemplo (no solo IT)
DEFAULT_SKILLS = [
    "Comunicación",
    "Trabajo en equipo",
    "Organización",
    "Office",
    "Atención al cliente",
    "Idiomas",
]


def _upsert_plan(db: Session, data: dict) -> Plan:
    plan = db.query(Plan).filter(Plan.key == data["key"]).first()
    if not plan:
        plan = Plan(**data, is_active=True, is_public=True)
        db.add(plan)
    else:
        # Sync comercial volumen (precio irresistible) + copy
        plan.name = data["name"]
        plan.description = data["description"]
        plan.price_cents = data["price_cents"]
        plan.currency = data.get("currency", plan.currency or "EUR")
        plan.interval = data.get("interval", plan.interval or "month")
        plan.sort_order = data.get("sort_order", plan.sort_order or 0)
        plan.features = data["features"]
        plan.entitlements = data["entitlements"]
        plan.is_active = True
        plan.is_public = True
    return plan


def _upsert_source(db: Session, src: dict) -> None:
    existing = db.query(JobSource).filter(JobSource.key == src["key"]).first()
    if not existing:
        db.add(
            JobSource(
                key=src["key"],
                name=src["name"],
                enabled=src.get("enabled", True),
                config=src.get("config") or {},
                region=src.get("region", "intl"),
                category=src.get("category", "general"),
                tier_min=int(src.get("tier_min", 0)),
                priority=int(src.get("priority", 100)),
                connector_type=src.get("connector_type", "html"),
            )
        )
        return
    # Sincronizar metadatos comerciales del catálogo
    existing.region = src.get("region", existing.region or "intl")
    existing.category = src.get("category", existing.category or "general")
    existing.tier_min = int(src.get("tier_min", existing.tier_min or 0))
    existing.priority = int(src.get("priority", existing.priority or 100))
    existing.connector_type = src.get("connector_type", existing.connector_type or "html")
    if src.get("name"):
        existing.name = src["name"]
    cfg = dict(existing.config or {})
    desired = dict(src.get("config") or {})
    for q in desired.get("queries") or []:
        have = list(cfg.get("queries") or [])
        if q not in have:
            have.append(q)
            cfg["queries"] = have
    if desired.get("search_url_template") and not cfg.get("search_url_template"):
        cfg["search_url_template"] = desired["search_url_template"]
    if desired.get("location") and not cfg.get("location"):
        cfg["location"] = desired["location"]
    existing.config = cfg
    flag_modified(existing, "config")


def seed_database(db: Session) -> None:
    settings = get_settings()

    plans_by_key: dict[str, Plan] = {}
    for pdata in DEFAULT_PLANS:
        p = _upsert_plan(db, pdata)
        plans_by_key[pdata["key"]] = p
    db.flush()

    for src in all_portal_definitions():
        _upsert_source(db, src)

    admin = db.query(User).filter(User.email == settings.admin_email).first()
    if not admin:
        admin = User(
            email=settings.admin_email,
            name=settings.admin_name,
            hashed_password=hash_password(settings.admin_password),
            is_admin=True,
            is_active=True,
        )
        db.add(admin)
        db.flush()
        db.add(
            Profile(
                user_id=admin.id,
                headline="Profesional en búsqueda activa",
                summary=(
                    "Perfil de ejemplo multi-sector. Configura roles, categorías y ubicación "
                    "para rankear ofertas de cualquier puesto (no solo tecnología)."
                ),
                skills=DEFAULT_SKILLS,
                experience_years=5,
                seniority="senior",
                languages=[
                    {"name": "Spanish", "level": "native"},
                    {"name": "English", "level": "intermediate"},
                ],
                english_fluent=False,
                salary_min=30000,
                salary_currency="EUR",
                remote_only=False,
                target_countries=["ES", "EU", "US", "Worldwide"],
                keywords=["empleo", "remoto", "teletrabajo", "Valencia"],
                desired_roles=["Cualquier puesto alineado al perfil"],
                job_categories=["general", "tech", "services"],
                employment_types=["full_time", "remote", "hybrid"],
                timezone="Europe/Madrid",
                location="Spain",
                work_authorization="Spain / EU",
            )
        )
    else:
        admin.is_admin = True
    admin.onboarding_done = True

    db.flush()
    max_plan = plans_by_key["carrera_max"]
    assign_plan(db, admin, max_plan, note="Admin = Carrera Max")

    # Asegurar suscripción free a usuarios sin plan
    free = plans_by_key["free"]
    for u in db.query(User).all():
        if u.is_admin:
            continue
        sub = db.query(Subscription).filter(Subscription.user_id == u.id).first()
        if not sub:
            db.add(Subscription(user_id=u.id, plan_id=free.id, status="active"))

    from app.services.job_urls import repair_dummy_job_urls

    repair_dummy_job_urls(db)
    db.commit()
