"""
DBML Parser and Helper Functions for Library Generator

Parses DBML schema and provides data transformations for template consumption.
"""

import re
from datetime import datetime, timedelta
from typing import Dict, List, Any


def parse_dbml(filepath: str) -> Dict[str, Any]:
    """
    Parse DBML file and return structured data.

    Returns:
        dict with 'tables' key containing list of table definitions
    """
    with open(filepath, 'r') as f:
        content = f.read()

    # Remove comments
    content = re.sub(r'//.*$', '', content, flags=re.MULTILINE)

    tables = []

    # Match Table definitions: "Table table_name { ... }"
    table_pattern = r'Table\s+(\w+)\s*\{([^}]+)\}'
    matches = re.finditer(table_pattern, content)

    for match in matches:
        table_name = match.group(1)
        table_body = match.group(2)

        fields = []
        # Match field definitions: "name type [constraints]"
        field_pattern = r'(\w+)\s+(\w+)(?:\s+\[([^\]]+)\])?'
        field_matches = re.finditer(field_pattern, table_body)

        for field_match in field_matches:
            field_name = field_match.group(1)
            field_type = field_match.group(2)
            constraints_str = field_match.group(3) or ""

            # Parse constraints
            constraints = _parse_constraints(constraints_str)

            field = {
                'name': field_name,
                'type': field_type,
                'dbml_type': field_type,
                'python_type': get_python_type(field_type),
                'sql_type': get_sqlite_type(field_type),
                'constraints': constraints,
                'is_pk': 'primary key' in constraints_str,
                'is_fk': 'ref:' in constraints_str,
                'is_nullable': 'not null' not in constraints_str,
            }
            fields.append(field)

        table = {
            'name': table_name,
            'fields': fields,
        }
        tables.append(table)

    return {
        'tables': tables,
        'table_count': len(tables),
        'all_fields': [f for t in tables for f in t['fields']],
    }


def _parse_constraints(constraints_str: str) -> str:
    """Parse constraint string and return SQL constraint clause."""
    constraints = []

    if 'primary key' in constraints_str:
        constraints.append('PRIMARY KEY')
    if 'not null' in constraints_str:
        constraints.append('NOT NULL')

    return ' '.join(constraints)


def get_python_type(dbml_type: str) -> str:
    """Convert DBML type to Python type."""
    type_map = {
        'integer': 'int',
        'int': 'int',
        'string': 'str',
        'text': 'str',
        'date': 'str',  # Will be stored as ISO string
        'datetime': 'str',
        'boolean': 'bool',
        'bool': 'bool',
        'float': 'float',
        'double': 'float',
    }
    return type_map.get(dbml_type.lower(), 'str')


def get_sqlite_type(dbml_type: str) -> str:
    """Convert DBML type to SQLite type."""
    type_map = {
        'integer': 'INTEGER',
        'int': 'INTEGER',
        'string': 'TEXT',
        'text': 'TEXT',
        'date': 'TEXT',
        'datetime': 'TEXT',
        'boolean': 'INTEGER',
        'bool': 'INTEGER',
        'float': 'REAL',
        'double': 'REAL',
    }
    return type_map.get(dbml_type.lower(), 'TEXT')


def get_sample_data() -> Dict[str, List[Dict[str, Any]]]:
    """
    Generate sample data for the library system.

    Returns:
        dict with 'authors', 'books', 'borrowers', 'loans' keys
    """
    authors = [
        {'id': 1, 'name': 'George Orwell', 'birth_year': 1903},
        {'id': 2, 'name': 'Harper Lee', 'birth_year': 1926},
        {'id': 3, 'name': 'J.K. Rowling', 'birth_year': 1965},
    ]

    books = [
        {'id': 1, 'title': '1984', 'isbn': '978-0451524935', 'author_id': 1},
        {'id': 2, 'title': 'Animal Farm', 'isbn': '978-0451526342', 'author_id': 1},
        {'id': 3, 'title': 'To Kill a Mockingbird', 'isbn': '978-0061120084', 'author_id': 2},
        {'id': 4, 'title': "Harry Potter and the Philosopher's Stone", 'isbn': '978-0747532699', 'author_id': 3},
        {'id': 5, 'title': 'Harry Potter and the Chamber of Secrets', 'isbn': '978-0747538494', 'author_id': 3},
    ]

    borrowers = [
        {'id': 1, 'name': 'Alice Johnson', 'email': 'alice@example.com'},
        {'id': 2, 'name': 'Bob Smith', 'email': 'bob@example.com'},
    ]

    today = datetime.now()
    loans = [
        {
            'id': 1,
            'book_id': 1,
            'borrower_id': 1,
            'loan_date': (today - timedelta(days=10)).strftime('%Y-%m-%d'),
            'return_date': (today - timedelta(days=2)).strftime('%Y-%m-%d'),  # Returned
        },
        {
            'id': 2,
            'book_id': 3,
            'borrower_id': 2,
            'loan_date': (today - timedelta(days=5)).strftime('%Y-%m-%d'),
            'return_date': None,  # Still active
        },
    ]

    return {
        'authors': authors,
        'books': books,
        'borrowers': borrowers,
        'loans': loans,
    }
