#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：login_template.py
模块描述：登录模板数据库模型定义

作者：czj
创建日期：2026-08-05
最后修改：2026-08-05
"""

from datetime import datetime
from typing import Optional
from sqlalchemy import String, Text, JSON, DateTime
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class LoginTemplate(Base):
    """
    登录模板数据库模型

    存储预置的登录流程模板，用于智能定位时自动执行登录和导航。

    Attributes:
        id (str): 模板唯一标识
        name (str): 模板名称
        description (str): 模板描述
        template_type (str): 模板类型：login/navigation/custom
        target_system (str): 目标系统名称
        base_url (str): 目标系统基础 URL
        steps (list): 登录/导航步骤定义，JSON 格式
        is_default (bool): 是否为默认模板
        status (str): 状态：active/disabled
        created_at (datetime): 创建时间
        updated_at (datetime): 更新时间

    Example:
        >>> template = LoginTemplate(
        ...     id="template_abc123",
        ...     name="统一管理平台登录模板",
        ...     template_type="login",
        ...     steps=[
        ...         {"order": 1, "action": "navigate", "params": {"url": "https://192.168.5.44"}},
        ...         {"order": 2, "action": "fill", "params": {"selector": "input[placeholder*='手机号']", "value": "admin@xty"}}
        ...     ]
        ... )
    """

    __tablename__ = "login_templates"

    id: Mapped[str] = mapped_column(String(64), primary_key=True, comment="模板ID")
    name: Mapped[str] = mapped_column(String(200), nullable=False, comment="模板名称")
    description: Mapped[str] = mapped_column(Text, default="", comment="模板描述")
    template_type: Mapped[str] = mapped_column(
        String(20),
        default="login",
        comment="模板类型: login/navigation/custom"
    )
    target_system: Mapped[str] = mapped_column(
        String(100),
        default="统一管理平台",
        comment="目标系统名称"
    )
    base_url: Mapped[str] = mapped_column(
        String(500),
        default="",
        comment="目标系统基础 URL（运行时以系统配置 TARGET_URL 为准）"
    )
    steps: Mapped[list] = mapped_column(JSON, default=list, comment="登录/导航步骤")
    is_default: Mapped[bool] = mapped_column(default=False, comment="是否为默认模板")
    status: Mapped[str] = mapped_column(
        String(20),
        default="active",
        comment="状态: active/disabled"
    )

    created_at: Mapped[datetime] = mapped_column(
        DateTime,
        default=datetime.utcnow,
        comment="创建时间"
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime,
        default=datetime.utcnow,
        onupdate=datetime.utcnow,
        comment="更新时间"
    )

    def __repr__(self) -> str:
        """字符串表示"""
        return f"<LoginTemplate(id={self.id}, name={self.name}, type={self.template_type})>"

    def to_dict(self) -> dict:
        """
        转换为字典

        Returns:
            dict: 模板数据字典
        """
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "template_type": self.template_type,
            "target_system": self.target_system,
            "base_url": self.base_url,
            "steps": self.steps or [],
            "is_default": self.is_default,
            "status": self.status,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
        }