"""Templates for the `strura gen:model` command."""

def schema_template(context: str, model_name: str, pascal_name: str, fields: list[dict]) -> str:
    """Generate the Pydantic schema file content."""
    field_lines = []
    for f in fields:
        py_type = f["py_type"]
        name = f["name"]
        constraints = f.get("constraints", {})
        
        field_args = []
        if constraints.get("default"):
            field_args.append(f"default={constraints['default']}")
        if constraints.get("examples"):
            field_args.append(f"examples={constraints['examples']}")
            
        arg_str = f", {', '.join(field_args)}" if field_args else ""
        field_lines.append(f"    {name}: {py_type} = Field(...{arg_str})")

    fields_block = "\n".join(field_lines)
    
    return f'''\
"""Domain schemas for the {pascal_name} entity."""

from pydantic import BaseModel, Field, ConfigDict
from datetime import datetime, date
from uuid import UUID
from typing import Optional

class {pascal_name}Base(BaseModel):
    """Base schema with common fields."""
    model_config = ConfigDict(from_attributes=True)

{fields_block}

class {pascal_name}Create({pascal_name}Base):
    """Schema for creating a new {pascal_name}."""
    pass

class {pascal_name}Update({pascal_name}Base):
    """Schema for updating an existing {pascal_name}."""
    pass

class {pascal_name}Response({pascal_name}Base):
    """Schema for {pascal_name} responses."""
    pass
'''

def model_template(context: str, model_name: str, pascal_name: str, db_schema: str, fields: list[dict]) -> str:
    """Generate the SQLAlchemy model file content."""
    field_lines = []
    for f in fields:
        sa_type = f["sa_type"]
        name = f["name"]
        constraints = f.get("constraints", {})
        
        col_args = [sa_type]
        if constraints.get("primary_key"):
            col_args.append("primary_key=True")
        if not constraints.get("nullable", True):
            col_args.append("nullable=False")
        if constraints.get("unique"):
            col_args.append("unique=True")
        if constraints.get("default"):
            col_args.append(f"default={constraints['default']}")
            
        arg_str = ", ".join(col_args)
        field_lines.append(f"    {name} = Column({arg_str})")

    fields_block = "\n".join(field_lines)
    
    return f'''\
"""SQLAlchemy model for the {pascal_name} entity."""

from sqlalchemy import Column, String, Integer, Float, Boolean, DateTime, Date, Enum, ForeignKey
from sqlalchemy.dialects.postgresql import UUID

from app.shared.infrastructure.database.models.base_model import BaseModel
from app.contexts.{context}.infrastructure.database.schema import TableName

class {pascal_name}(BaseModel):
    """Database model for {pascal_name}."""
    
    __tablename__ = TableName.{model_name.upper()}
    __table_args__ = {{"schema": "{db_schema}"}}

{fields_block}
'''

def data_dictionary_template(context: str, model_name: str, pascal_name: str, fields: list[dict]) -> str:
    """Generate the Data Dictionary Markdown content."""
    table_rows = []
    for f in fields:
        name = f["name"]
        py_type = f["py_type"]
        constraints = f.get("constraints", {})
        desc = constraints.get("description", "No description provided.")
        
        constr_vals = []
        if constraints.get("primary_key"):
            constr_vals.append("PK")
        if not constraints.get("nullable", True):
            constr_vals.append("NOT NULL")
        if constraints.get("unique"):
            constr_vals.append("UNIQUE")
        
        constr_str = ", ".join(constr_vals) if constr_vals else "-"
        table_rows.append(f"| `{name}` | `{py_type}` | {constr_str} | {desc} |")

    table_block = "\n".join(table_rows)
    
    return f'''\
# Data Dictionary: {pascal_name}

**Context**: `{context}`  
**Type**: `Database Model` / `Domain Schema`  
**Table**: `TableName.{model_name.upper()}`

## Overview

Purpose of the {pascal_name} entity.

## Fields

| Field Name | Type | Constraints | Description |
|------------|------|-------------|-------------|
{table_block}

## Business Rules

1. TBD
'''
