# Path: artisans/mimic/generator.py
# ---------------------------------

from typing import Dict, Any


class MockServerForge:
    """
    Transmutes a Schema into an executable FastAPI Server.
    """

    def __init__(self, framework: str = "fastapi"):
        self.framework = framework

    def forge_server(self, schema: Dict[str, Any], port: int) -> str:
        name = schema['name']
        slug = name.lower()

        # Generate the Faker logic map
        faker_map = self._generate_faker_map(schema['fields'])

        return f"""
# Auto-generated by Scaffold Simulacrum
import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from faker import Faker
import random

fake = Faker()

app = FastAPI(title="{name} Simulacrum")

# --- Domain Model ---
class {name}(BaseModel):
    {self._render_pydantic_fields(schema['fields'])}

# --- In-Memory Database ---
db = []

def generate_fake_{slug}() -> {name}:
    return {name}(
        {faker_map}
    )

# Seed Initial Data
for _ in range(10):
    db.append(generate_fake_{slug}())

# --- Endpoints ---

@app.get("/{slug}s", response_model=List[{name}])
def list_{slug}s():
    return db

@app.get("/{slug}s/{{item_id}}", response_model={name})
def get_{slug}(item_id: int):
    # Mock lookup
    found = next((item for item in db if getattr(item, 'id', -1) == item_id), None)
    if not found:
        # Fallback if no ID field or not found, return random for simulation
        return random.choice(db)
    return found

@app.post("/{slug}s", response_model={name})
def create_{slug}(item: {name}):
    db.append(item)
    return item

if __name__ == "__main__":
    print(f"🔮 Simulacrum manifested at http://localhost:{port}")
    uvicorn.run(app, host="127.0.0.1", port={port})
"""

    def _render_pydantic_fields(self, fields: Dict[str, str]) -> str:
        lines = []
        for name, type_hint in fields.items():
            lines.append(f"{name}: {type_hint}")
        return "\n    ".join(lines)

    def _generate_faker_map(self, fields: Dict[str, str]) -> str:
        """Heuristic mapping of field names to Faker methods."""
        mapping = []
        for name, _type in fields.items():
            val = "None"
            n = name.lower()
            if "id" in n:
                val = "random.randint(1, 1000)"
            elif "email" in n:
                val = "fake.email()"
            elif "name" in n:
                val = "fake.name()"
            elif "address" in n:
                val = "fake.address()"
            elif "url" in n:
                val = "fake.url()"
            elif "int" in _type:
                val = "random.randint(0, 100)"
            elif "bool" in _type:
                val = "fake.boolean()"
            elif "str" in _type:
                val = "fake.word()"

            mapping.append(f"{name}={val}")
        return ",\n        ".join(mapping)